C++ solution


  • 0
    B

    count sum of all subtree, there need to be a number is half of the sum at root

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool checkEqualTree(TreeNode* root) {
            unordered_map<int,int>sum_count;
            int sum = getSum(sum_count, root);
            if(sum % 2 != 0) return false;
            if(sum == 0) return sum_count[0] > 1;
            return sum_count[sum/2];
        }
        
        int getSum(unordered_map<int,int> & sum_count, TreeNode* root)
        {
            if(!root) return 0;
            int val = root -> val + getSum(sum_count, root -> left) + getSum(sum_count, root -> right);
            sum_count[val]++;
            return val;
        }
    };

Log in to reply
 

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