1198. Most Frequent Subtree Sum

Code(Language:C++)
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the root
     * @return: all the values with the highest frequency in any order
     */
    unordered_map<int, int> mp;  
    vector<int> findFrequentTreeSum(TreeNode * root) {
        // Write your code here
        vector<int> res; 
        if(root == NULL){
            return res; 
        }
        findSum(root); 
        int maxV = INT_MIN; 
        for(auto i : mp){
            maxV = max(maxV, i.second); 
        }
        for(auto i: mp){
            if(i.second == maxV){
                res.push_back(i.first); 
            }
        }
        return res; 
    }
    int findSum(TreeNode *root){
        if(root == NULL){
            return 0; 
        }
        int left = findSum(root->left);
        int right = findSum(root->right); 
        int sum = left + right + root->val; 
        mp[sum]++;
        return sum; 
    }
};

Comments

Popular posts from this blog

1427. Split Array into Fibonacci Sequence

Amazon OA 763. Partition Labels

05/25 周一