Leetcode刷题(19)

Given the root of a tree, youare asked to find the most frequent subtree sum. The subtree sum of a node isdefined as the sum of all the node values formed by the subtree rooted at thatnode (including the node itself). So what is the most frequent subtree sumvalue? If there is a tie, return all the values with the highest frequency inany order.

Examples 1
Input:

  5
 /  \
2   -3

return [2,-3, 4], since all the values happen only once, return all of them in any order.

Examples 2
Input:

  5
 /  \
2   -5

return [2],since 2 happens twice, however -5 only occur once.

Note: You may assume the sum of values in any subtree is in the rangeof 32-bit signed integer.

Subscribe tosee which companies asked this question.

/**

 * Definition for abinary 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) {

       unordered_map<int,int> counts;

        int maxsum =0;

       

       countSubtreeSums(root,counts,maxsum);

       vector<int> maxsums;

        for(constauto &x : counts) {

            if(x.second== maxsum) maxsums.push_back(x.first);

        }

        returnmaxsums;

       

    }

   

    intcountSubtreeSums(TreeNode* r, unordered_map<int,int> &counts,int&maxsum) {

        if(r ==nullptr) return 0;

        int sum =r->val;

        sum +=countSubtreeSums(r->left,counts,maxsum);

        sum +=countSubtreeSums(r->right,counts,maxsum);

       

       ++counts[sum];

        maxsum =max(maxsum, counts[sum]);

        return sum;

    }

};

猜你喜欢

转载自blog.csdn.net/dlfxjc2/article/details/70215224