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 ...
随机推荐
- ranch分析学习(二)
紧接上篇,今天我们来分析监督树的工作者,打工仔执行任务的人.废话不多少我们直接进入正题. 3.ranch_server.erl 整个文件的功能主要是存储tcp对应参数的的信息.信息的存储方式采用的 ...
- 每天一个linux命令(性能、优化):【转载】top命令
top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况,类似于Windows的任务管理器.下面详细介绍它的使用方法.top是一个动态显示过程,即可以通过用户按键来不断刷新 ...
- sql中的一些函数(长期更新。。)
前言 在最近看别人的sql的时候,看到一些函数,比如left(),right()等等,好奇是什么意思,查询之后觉得还是挺有用的,特此记录下来.博客会在遇到新的函数的时候定期更新. 正文 1. left ...
- Xcode ARC需要什么版本的环境支持
Mac OS X v10.6 和 v10.7 (64位应用) 的Xcode 4.2以上版本支持ARC,iOS 4 和 iOS 5 下ARC都能工作,但Weak不支持Mac OS X v10.6 和 i ...
- Nchan 实时消息 安全配置
备注: 即时消息的安全对于我们来说是比较重要的,作者在设计Nchan 的时候已经考虑了 a. nchan_authorize_request (Hooks and Callbacks)可以集成 ...
- Vim使用YouCompleteMe达到类似IDE的代码提示、补全,以及其他实用设置
接触Linux有两年了,vim还是只会简单的操作.最近实在受不了sublime的代码提示,决定花点时间来配置下vim.本文讲自己认为方便的vim配置,称不上完美,只讲究简单实用. 使用 ctags 主 ...
- ecmall页面空白解决方案(转)
页面空白解决方案: ------------------------------------------------------------------------------------------ ...
- jQuery实现清空table表格除首行外的所有数据
1.其实网上有很多版本,试了好几个都不行,最后还是查到了一个非常方便的:不会清除表格第一行表头部分. 其中J_tab_fam是table的id. ? 1 $("#J_tab_fam tr: ...
- Vmvare + Ubuntu 16.04环境搭建 + 相关软件安装配置笔记【深度学习】
前言 由于学习与工作的需要,加上之前配置好的vmmachines都损坏了,我就重新弄一个ubuntu虚拟机,配置一下环境,给自己留个记录 1.文件 2.配置过程 1.在Vmware中新建虚拟机,自定义 ...
- Unit04: 实战技巧 、 登录
Unit04: 实战技巧 . 登录 使用注解方式简化Unit04的小程序. 1. 基于注解的springmvc应用程序的开发 (1)编程步骤 step1. 导包. step2. 添加spring配置文 ...