原题地址:点我传送
指向很明确,就是要用map容器,或者是做哈希表,思想都一样,java这方面还不是很熟,先用的C++来做。
首先明确肯定是后序遍历计算sum,然后让sum对应的count++,并与记录最大值的maxCount比较。最后再遍历整个map容器,count==maxCount的就可以放进ans向量里。注意传递要使用按引用传递。
C++:
/**
* 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) {
int maxCount = 0;
unordered_map <int,int> sumToCounts;
count(root,sumToCounts,maxCount);
vector<int> ans;
for(auto& x : sumToCounts)
{
if(x.second==maxCount) ans.push_back(x.first);
}
return ans;
}
int count(TreeNode* root,unordered_map <int,int> &sumToCounts, int& maxCount)
{
if(root==nullptr)return 0;
int sum = root-> val;
sum += count(root->left,sumToCounts,maxCount);
sum += count(root->right,sumToCounts,maxCount);
sumToCounts[sum]++;
maxCount = (sumToCounts[sum] > maxCount ? sumToCounts[sum] : maxCount);
return sum;
}
};
Java:
要注意map容器中int换成了Integer,涉及的用法有keySet,get,getOrDefault,put。由于是类,可以把要按引用传递的变量当作类里的数据成员,vector换成了List,用法有size,get,add。最后还多了一步把它转换成数组。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
Map <Integer, Integer> sumToCounts;
int maxCount;
public int[] findFrequentTreeSum(TreeNode root) {
sumToCounts = new HashMap <Integer, Integer> ();
count(root);
List <Integer> ans = new ArrayList <> ();
for(int x : sumToCounts.keySet())
{
if(sumToCounts.get(x) == maxCount) ans.add(x);
}
int answer[] = new int [ans.size()];
for(int i=0;i<ans.size();i++)
{
answer[i] = ans.get(i);
}
return answer;
}
int count(TreeNode root)
{
if(root==null)return 0;
int sum = root.val;
sum += count(root.left);
sum += count(root.right);
int count = sumToCounts.getOrDefault(sum,0)+1;
sumToCounts.put(sum, count);
maxCount = (count > maxCount ? count : maxCount);
return sum;
}
}