Leetcode刷题(19)
来源:互联网 发布:使命召唤12中文优化 编辑:程序博客网 时间:2024/06/06 19:17
Given the root of a tree, youare asked to find the most frequent subtree sum. The subtree sum of a node isdefined as the sum of all the node values formed by the subtree rooted at thatnode (including the node itself). So what is the most frequent subtree sumvalue? If there is a tie, return all the values with the highest frequency inany order.
Examples 1
Input:
5
/ \
2 -3
return [2,-3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:
5
/ \
2 -5
return [2],since 2 happens twice, however -5 only occur once.
Note: You may assume the sum of values in any subtree is in the rangeof 32-bit signed integer.
Subscribe tosee which companies asked this question.
/**
* Definition for abinary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL),right(NULL) {}
* };
*/
class Solution {
public:
vector<int>findFrequentTreeSum(TreeNode* root) {
unordered_map<int,int> counts;
int maxsum =0;
countSubtreeSums(root,counts,maxsum);
vector<int> maxsums;
for(constauto &x : counts) {
if(x.second== maxsum) maxsums.push_back(x.first);
}
returnmaxsums;
}
intcountSubtreeSums(TreeNode* r, unordered_map<int,int> &counts,int&maxsum) {
if(r ==nullptr) return 0;
int sum =r->val;
sum +=countSubtreeSums(r->left,counts,maxsum);
sum +=countSubtreeSums(r->right,counts,maxsum);
++counts[sum];
maxsum =max(maxsum, counts[sum]);
return sum;
}
};
- Leetcode刷题(19)
- LeetCode刷题(19)
- 【leetcode】leetcode 刷题 笔记 (不定期更新)
- leetcode刷题(Python)
- LeetCode刷题(1)
- LeetCode刷题(2)
- LeetCode刷题(3)
- LeetCode刷题(废弃)
- LeetCode刷题(FizzBuzz)
- Leetcode刷题(1)
- Leetcode刷题(2)
- Leetcode刷题(3)
- Leetcode刷题(4)
- Leetcode刷题(5)
- Leetcode刷题(6)
- Leetcode刷题(7)
- Leetcode刷题(13)
- Leetcode刷题(17)
- thinkphp field()方法的作用
- 给初学者的RxJava2.0教程(三)
- Codeforces Round #409 (rated, Div. 2, based on VK Cup 2017 Round 2) D. Volatile Kite
- PL/SQL 存储过程学习
- SRM548 Div1Medium KingdomAndDice
- Leetcode刷题(19)
- Android内存泄漏的八种可能
- 深入理解JVM笔记之内存管理机制
- Git远程仓库
- 用matlab求计算机所能表示的最大正数和最小正数
- 主板芯片集与内存映射
- Linux shell中将多行内容赋值给一个变量 && 常用的转移字符
- 分数加减法
- Android中将布局文件/View添加至窗口过程分析 ---- 从setContentView()谈起