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 ...
随机推荐
- ubuntu 添加应用到Dash启动器
打开终端输入 $sudo vim /usr/share/applications/name.desktop name是你的程序标识名称 在打开的编辑器中添加以下内容,这里以配置NetBeans为例: ...
- 跳转后全屏,兼容大部分浏览器JavaScript
<!DOCTYPE html> <html> <head> <title>测试</title> </head> <body ...
- BZOJ - 3223 Tyvj 1729 文艺平衡树 (splay/无旋treap)
题目链接 splay: #include<bits/stdc++.h> using namespace std; typedef long long ll; ,inf=0x3f3f3f3f ...
- java分布式(一)
分布式架构的演进 初始阶段架构 应用服务和数据服务分离阶段 使用缓存改善性能 使用应用服务器集群 数据库读写分离 反向代理和CDN加速 分布式文件系统和分布式数据库 使用NoSql和搜索引擎 业务拆分 ...
- 20179223《Linux内核原理与分析》第二周学习笔记
第二周实验 本周学习情况: 学习了X86 cpu的几个寄存器及X86汇编指令: movl %eax,%edx edx=eax %表示一个寄存器,把eax内容放入edx,等号相当于把eax赋值给edx, ...
- python 打印对象所有属性值
from pprint import pprint pprint (vars(your_object)) 另外查看所有属性名用.__dict__
- drone 学习一 几个核心组件
1. clone 这个是内置的,实际上就行进行代码clone的 参考配置,同时我们可以使用自定义的插件 clone: + git: + image: plugins/git pipeline: bui ...
- fail2ban的介绍
fail2ban的介绍 http://www.jb51.net/article/48591.htm http://lilinji.blog.51cto.com/5441000/1784726 fail ...
- eclipse导出jar,再转换为exe可执行程序
转自: https://blog.csdn.net/mommomm/article/details/8227876 若只想知道如何把jar转换成exe,直接看第四步即可. 一.导出jar文件: 选中你 ...
- js的delegate回调例子
暂时没发现有具体的实际用处,先记录下 <!DOCTYPE html> <html> <head lang="en"> <meta char ...