C++ easy to understand simple code

  • 0

    Get the total sum of the tree while also updating each node's value to contain sum of its subtree and itself. Then perform a second traversal to check if the tree could be partitioned equally. If changing the original node value is not allowed, we could store the subtree sum at each node in a map.

     * 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 {
        bool checkEqualTree(TreeNode* root) {
            if (!root->left && !root->right) return false;
            int sum = sumTree(root);
            return checkEqual(root, sum);
        bool checkEqual(TreeNode* root, int sum){
            if (!root) return false;
            if (sum-2*root->val==0)
                return true;
            return checkEqual(root->left, sum) || checkEqual(root->right, sum);
        int sumTree(TreeNode* root){
            if (!root) return 0;
            root->val += sumTree(root->left) + sumTree(root->right);
            return root->val;

Log in to reply

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