leetcode508
/**
* 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的更多相关文章
- [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 ...
随机推荐
- AspectJ语法
AspectJ语法 看了很多AOP的文章了,AOP这两年发展的很慢,没有什么新意,现在到处都是SOA,SCA了,不过研究了一下,觉得还是很有帮助的.尤其是增加系统的契约性和模块的独立性来说,很有帮助. ...
- IAuthenticationManager.SignOut 退不了
AuthenticationManager.SignOut(); 这个退不了,然后就加上 AuthenticationManager.SignOut( DefaultAuthenticatio ...
- BZOJ2243 SDOI2011 染色 【树链剖分】
BZOJ2243 SDOI2011 染色 Description 给定一棵有n个节点的无根树和m个操作,操作有2类: 1.将节点a到节点b路径上所有点都染成颜色c: 2.询问节点a到节点b路径上的颜色 ...
- iOS 信号量解决-网络异步请求的数据同步返回问题
有那么一个场景如下 +PayWithBlock:(NSString*(^)(NSString *message)) block; 如果 block 返回是同步的那是没有问题的,但是如果block 内容 ...
- 让Apache支持URL重写
第一步: 添加.htaccess文件 Rewrite 规则 <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_ ...
- phoenix 使用activerecord模式框架ecto 访问数据库
备注: 需要先安装mysql 以及phoenix 框架,测试使用的是docker 进行安装,具可以参考代码 1. 创建项目 mix phx.new first --database mys ...
- 解决Vsphere Client 60天过期问题
- centos6.6安装SVN服务器(2015/3/7)
一.安装#yum install subversion 判断是否安装成功 [root@]# svnserve --version有了SVN软件后还需要建立SVN库.#mkdir /opt/svn/ ...
- 常见企业IT支撑【4、gitlab代码管理工具】
安装方式可借鉴http://www.cnblogs.com/juandx/p/5339254.html 安装方式
- OPC UA (统一架构)的优势
OPC UA OPC统一架构(OPC Unified Architecture)是OPC基金会(OPC Foundation)创建的新技术,更加安全.可靠.中性(与供应商无关),为制造现场到生产计划或 ...