simple c++ solution


  • 0
    A
    private:
        unordered_map<int, int> table;
        int cur_sum = 0;
    public:
        vector<int> findFrequentTreeSum(TreeNode* root) {
            find_subtree(root);
            vector<int> res;
            auto it = table.begin();
            int max = 0;
            for(; it != table.end(); it++){
                if(it->second > max){
                    res.clear();
                    res.push_back(it->first);
                    max = it->second;
                }
                else if(it->second == max){
                    res.push_back(it->first);
                }
            }
            return res;
            
        }
        
        void find_subtree(TreeNode* root){
            if(!root) return ;
            
            if(root->right) find_subtree(root->right);
            if(root->left) find_subtree(root->left);
            
            root->val += (root->left? root->left->val:0) + (root->right? root->right->val:0);
            if(table.find(root->val) == table.end()){
                    table[root->val] = 1;
                }
            else{
                auto it = table.find(root->val);
                it->second++;
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.