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 ...
随机推荐
- Android中的按键顺序打乱
首先要找到相对应的控件,之后再来一个数组,再把数组里面的数字显示到控件上面. private void initView() { mNum0 = (Button) findViewById(R.id. ...
- 两个线程与stringbuffer和stringbuiler以及lock synchronized线程测试
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public clas ...
- BZOJ3144 Hnoi2013 切糕 【网络流】*
BZOJ3144 Hnoi2013 切糕 Description Input 第一行是三个正整数P,Q,R,表示切糕的长P. 宽Q.高R.第二行有一个非负整数D,表示光滑性要求.接下来是R个P行Q列的 ...
- Quartz 2D编程指南(2) - 图形上下文
一个Graphics Context表示一个绘制目标.它包含绘制系统用于完成绘制指令的绘制参数和设备相关信息.Graphics Context定义了基本的绘制属性,如颜色.裁减区域.线条宽度和样式信息 ...
- pat甲级 1154 Vertex Coloring (25 分)
A proper vertex coloring is a labeling of the graph's vertices with colors such that no two vertices ...
- java 乐观锁CAS
乐观锁是一种思想,本身代码里并没有lock或synchronized关键字进行修饰.而是采用一种version. 即先从数据库中查询一条记录得到version值,在更新这条记录时在where条件中对这 ...
- piwik docker 安装
备注: 生产环境使用docker-compose 1. 安装docker && docker-compose 此处略过 2. 下载docker-compose 的文件 h ...
- drill 数据源配置补充
1. mongodb { "type":"mongo", "connection":"mongodb://user:passwor ...
- UVA12716 GCD XOR 数论数学构造
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u010682557/article/details/36204645 题目给你一个N,让你求 两个数 ...
- 基于Video4Linux的视频采集模块开发(转)
Linux系统中,摄像头驱动程序安装好后,为了进行视频采集必须加入Video4Linux模块,从而可以通过Video4Linux模块提供的编程接口(API)从摄像头设备中获取图像帧.下面具体研究基于V ...