508. Most Frequent Subtree Sum
来源:互联网 发布:手机版windows系统 编辑:程序博客网 时间:2024/05/22 07:02
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.
这道题其实就是采用深度优先搜索的算法,然后再用了Map来存储数据,这里要注意的是root对应的节点的值,这里用val表示。然后就是注意最后dfs,是if和if和if,因为任何存在的可能的和都得算一次。然后再回到原函数,把最大次数的和求出来,然后再把所有出现次数等于maxx的数压入vector,这里注意是把对应的和压入,而不是把次数压入。
代码如下:
/** * 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 {private: map<int,int>m;public: vector<int> findFrequentTreeSum(TreeNode* root) { dfs(root); vector<int>v; int maxx=-100; for(auto it=m.begin();it!=m.end();it++){ maxx=max(maxx,it->second); } for(auto it=m.begin();it!=m.end();it++){ if(maxx==it->second){ v.push_back(it->first); } } return v; } void dfs(TreeNode* root){ if(root==NULL)return; if(root->left!=NULL){ dfs(root->left); root->val+=root->left->val; } if(root->right!=NULL){ dfs(root->right); root->val+=root->right->val; } m[root->val]++; }};
0 0
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- Most Frequent Subtree Sum
- Most Frequent Subtree Sum
- Leetcode-508. Most Frequent Subtree Sum
- [leetcode] 508. Most Frequent Subtree Sum
- LeetCode 508. Most Frequent Subtree Sum
- Leetcode 508. Most Frequent Subtree Sum
- leetcode题解-508. Most Frequent Subtree Sum
- 用git上传项目到GitHub
- 535. Encode and Decode TinyURL
- 权限管理项目
- Linux系统备份与还原
- ngin日志管理
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- javaSE学习12_foreach循环
- 机器学习入门系列-为什么要机器学习
- Opencontrail 流的处理
- ESP8266最小系统板以及下载方式
- linux grep命令详解
- 图像处理之插值运算
- 碰到的一些面试问题