Most Frequent Subtree Sum

原题地址:点我传送

指向很明确,就是要用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 findFrequentTreeSum(TreeNode* root) {
        int maxCount = 0;
        unordered_map  sumToCounts;
        count(root,sumToCounts,maxCount);
        vector ans;
        for(auto& x : sumToCounts)
        {
            if(x.second==maxCount) ans.push_back(x.first);
        }
        return ans;
    }
    int count(TreeNode* root,unordered_map  &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  sumToCounts;
    int maxCount;
    public int[] findFrequentTreeSum(TreeNode root) {
        sumToCounts = new HashMap  ();
        count(root);
        List  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 maxCount ?  count : maxCount);
        return sum;
    }
}



你可能感兴趣的:(LeetCode)