[663. Equal Tree Partition] C++ AC


  • 0
    class Solution {
    public:
    bool checkEqualTree(TreeNode* root) {
        if(root == nullptr) return false;
        unordered_map<int, int> mp;
        int total = 0;
        sum(root, mp, 1, total);
        for(auto m : mp){
            if((m.second * 2) == total && m.first != 1) return true;
        }
        return false;
    }
    
    int sum(TreeNode* root, unordered_map<int, int>& mp, int i, int& total){
        if(root == nullptr) return 0;
        int left_sum = sum(root->left, mp, 2*i, total);
        int right_sum = sum(root->right, mp, 2*i + 1, total);
        mp[i] = root->val + left_sum + right_sum;
        total += root->val;
        return mp[i];
    }
    };

Log in to reply
 

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