508. Most Frequent Subtree Sum

1. Description

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.

2. Note

  • You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

3. Solutions

My Accepted Solution

n is the number of nodes in i_root
Time complexity: O(n)
Space complexity: O(n)

class Solution 
{
private:
    unordered_map<int, int> timesOfSum;
    
    int preorderTraverse(TreeNode *i_root)
    {
        if(!i_root->left && !i_root->right)
        {
            timesOfSum[i_root->val]++;
            return i_root->val;
        }
        
        int leftChildSum = (i_root->left ? preorderTraverse(i_root->left) : 0);
        int rightChildSum = (i_root->right ? preorderTraverse(i_root->right) : 0);
        timesOfSum[i_root->val + leftChildSum + rightChildSum]++;
        
        return i_root->val + leftChildSum + rightChildSum;
    }
    
public:
    // vector<int> findFrequentTreeSum(TreeNode* root)
    vector<int> findFrequentTreeSum(TreeNode *i_root) 
    {
        if(!i_root) return vector<int>{};
        
        preorderTraverse(i_root);
        
        int mostTimes = 0;
        vector<int> result;
        for(auto iter : timesOfSum)
        {
            if(iter.second == mostTimes)
            {
                result.push_back(iter.first);
            }
            else if(iter.second > mostTimes)
            {
                result.clear();
                result.push_back(iter.first);
                mostTimes = iter.second;
            }
        }
        
        return result;
    }
};
comments powered by Disqus