LeetCode
来源:互联网 发布:知乎什么时候成立的 编辑:程序博客网 时间:2024/06/10 14:30
Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.
Examples 1
Input:
5 / \2 -3return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:
5 / \2 -5return [2], since 2 happens twice, however -5 only occur once.
Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.
问在一棵二叉树中,子树和最多的值是多少,如果有多个,返回多个。
用一个map存一下数量,最后遍历map更新ans,时间复杂度O(n)。
/** * Definition for a binary 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) { vector<int> ans; if (!root) return ans; unordered_map<int, int> cnt; int mmax = 0; solve(root, cnt, mmax); for (auto x: cnt) { if (x.second == mmax) ans.push_back(x.first); } return ans; } int solve(TreeNode* root, unordered_map<int, int> &cnt, int &mmax) { if (!root) return 0; int sum = root->val; sum += solve(root->left, cnt, mmax) + solve(root->right, cnt, mmax); cnt[sum]++; mmax = max(cnt[sum], mmax); return sum; }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- 简单实现高度平滑变化的ViewPager
- ArrayList和LinkedList的区别
- Floyd算法
- 牛客面经 | BAT、美团、360、滴滴新锐……2W字干货,这不仅仅是一篇面经
- Please allow Subclipse team to receive anonymous usage statistics for this Eclipse intance(info)
- LeetCode
- 神经网络中权值初始化的方法
- ubuntu16.04下安装phpmyadmin
- css实现div层透明毛玻璃
- CSDN日报20170727——《想提高团队技术,来试试这个套路!》
- 3252. Round Numbers
- 合并游戏 737(区间Dp
- shell中curl 用法详解 (二)
- 2017多校训练赛第二场 HDU 6053 TrickGCD(容斥原理/莫比乌斯反演)