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 ...
随机推荐
- 利用gcc 4.4 优化的方法
Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE /* Style Definitions */ table.MsoNormalTable ...
- SVM处理多分类问题(one-versus-rest和one-versus-one的不同)
SVM算法最初是为二值分类问题设计的,当处理多类问题时,就需要构造合适的多类分类器. 目前,构造SVM多类分类器的方法主要有两类:一类是直接法,直接在目标函数上进行修改,将多个分类面的参数求解合并到一 ...
- Uva12230Crossing Rivers (数学期望)
问题: You live in a village but work in another village. You decided to follow the straight path betwe ...
- HDU3853LOOPS (师傅逃亡系列•三)(基础概率DP)
Akemi Homura is a Mahou Shoujo (Puella Magi/Magical Girl). Homura wants to help her friend Madoka sa ...
- pandas 的Series 里经常会出现DatetimeIndex这个类
DatetimeIndex 的操作还是值得研究一下的. 参考其用法, http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Date ...
- Python中super()和__init__()方法
采用新式类,要求最顶层的父类一定要继承于object,这样就可以利用super()函数来调用父类的init()等函数, 每个父类都执行且执行一次,并不会出现重复调用的情况.而且在子类的实现中,不用到处 ...
- quick 状态机StateMachine
function Player:addStateMachine() self.fsm_ = {} cc.GameObject.extend(self.fsm_) :addComponent(" ...
- JDK1.5java新特性
JDK1.5java增加的新特性: 自动装箱/拆箱 增强for 泛型 枚举 静态导入 可变参数 1 自动装箱/拆箱 * JDK1.5允许开发人员把一个基 ...
- springboot中 简单的SpringMvc全局异常处理
1.全局异常处理类:GlobalExceptionHandler.java package com.lf.exception; import java.util.HashMap; import jav ...
- vim初探
https://github.com/spf13/spf13-vim 安装了此博主的开源项目. :vsp ——竖分屏 :sp ——横分屏