/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
Stack<TreeNode> S = new Stack<TreeNode>();
private void postNode(TreeNode node)
{
if (node != null)
{
S.Push(node);//先序遍历,遍历所有节点
if (node.left != null)
{
postNode(node.left);
}
if (node.right != null)
{
postNode(node.right);
}
}
} private int sumSubTree(TreeNode node)
{
if (node != null)
{
var sum = node.val;
if (node.left != null)
{
sum += sumSubTree(node.left);
}
if (node.right != null)
{
sum += sumSubTree(node.right);
}
return sum;
}
else
{
return ;
} } public int[] FindFrequentTreeSum(TreeNode root)
{
if (root == null)
{
return new int[] { };
}
postNode(root);
var list = S.ToList();
Dictionary<int, int> dic = new Dictionary<int, int>();//key是sum值,value是次数
foreach (var l in list)
{
var sum = sumSubTree(l);
if (!dic.ContainsKey(sum))
{
dic.Add(sum, );
}
else
{
dic[sum]++;
}
} var result = dic.OrderByDescending(x => x.Value).ToList(); var max = int.MinValue;
var arylist = new List<int>();
foreach (var r in result)
{
var count = r.Value;
var cur = r.Key;
if (count >= max)
{
max = count;
arylist.Add(cur);
}
else
{
break;
}
} var ary = arylist.ToArray();
return ary;
}
}

https://leetcode.com/problems/most-frequent-subtree-sum/#/description

leetcode508的更多相关文章

  1. [Swift]LeetCode508. 出现次数最多的子树元素和 | Most Frequent Subtree Sum

    Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a ...

随机推荐

  1. ubuntu 下使用etcd

    1.安装ETCD_VER=v3.1.0 DOWNLOAD_URL=https://github.com/coreos/etcd/releases/download curl -L ${DOWNLOAD ...

  2. [javascript]复制到剪切板

    <!-- 一个简单的小栗子 --> <button class="copy-link" data-fulllink="要被复制的内容在这里-" ...

  3. Linux下iptables介绍

    ptables简介 iptables是基于内核的防火墙,功能非常强大,iptables内置了filter,nat和mangle三张表. filter负责过滤数据包,包括的规则链有,input,outp ...

  4. JAXP使用Stax API时格式化输出XML 2

    之前实现的一个版本:http://www.cnblogs.com/lyhtbc/p/jaxp-pretty-format-validate-validation-stax-stax2.html 这个版 ...

  5. ubuntu下codeblock美化

    1.备份配置文件:default.conf. 2.将default.conf中的内容替换为最下面代码,并保存. 3.打开codeblock,Setting-Editor-Syntax,然后选择Colo ...

  6. WIN7下配置和使用解压缩版MYSQL

    最近mysql出了新的GA版本——mysql5.6.11,此版本windows64位下只有解压缩版,于是在win7上进行了配置.期间碰到了一些问题,在此记录一下. 一.环境 操作系统:WIN764位 ...

  7. Java并发--如何创建线程

    下面是本文的目录大纲: 一.Java中关于应用程序和进程相关的概念 二.Java中如何创建线程 三.Java中如何创建进程 转载原文链接:http://www.cnblogs.com/dolphin0 ...

  8. 流畅设计 Fluent Design System 中的光照效果 RevealBrush,WPF 也能模拟实现啦!

    UWP 才能使用的流畅设计效果好惊艳,写新的 UWP 程序可以做出更漂亮的 UI 啦!然而古老的 WPF 项目也想解解馋怎么办? 于是我动手实现了一个!   迫不及待看效果 ▲ 是不是很像 UWP 中 ...

  9. Makefile常用知识点

    格式 目标:最终要去生成的文件, 定格写,后面是冒号(冒号后面是依赖) 依赖:用来生成目标的源材料 命令:加工的方法,命令前面一定是Tab, make的过程就是使用命令将依赖加工成目标的过程 工作原理 ...

  10. PAT1034. Head of a Gang ——离散化+并查集

    题意:成员A与成员B通话 ,成员B与成员C通话,则 ABC即为一个团伙,一共有若干个团伙,每个团伙的人数大于2且相互通话时间超过一定值即为黑帮,每个黑帮伙里有一个BOSS,boss是与各个成员打电话最 ...