/**
* 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:
int dfs(TreeNode* now,int& mxf,map<int,int>& mp){
int sum = now->val;
if(now->left != NULL) sum += dfs(now->left,mxf,mp);
if(now->right != NULL) sum += dfs(now->right,mxf,mp);
mp[sum]++;
mxf = max(mxf,mp[sum]);
return sum;
}
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> ans;
if(root == NULL) return ans;
map<int,int> mp;
int mxf = 1;
dfs(root,mxf,mp);
for(map<int,int>::iterator p=mp.begin();p!=mp.end();p++){
if(p->second == mxf){
ans.push_back(p->first);
}
}
return ans;
}
};
No.102 - LeetCode508
最新推荐文章于 2022-06-19 17:11:27 发布
本文介绍了一个用于查找二叉树中出现频率最高的节点和的算法。通过深度优先搜索(DFS)遍历二叉树,计算每个节点的和,并使用映射记录每个和的出现次数。最终返回出现次数最多的节点和。
606

被折叠的 条评论
为什么被折叠?



