C++ Recursive no extra memory


  • 0
    J
    class Solution {
    public:
        bool checkEqualTree(TreeNode* root) {
            if(root == NULL)
                return false;
            int sum=sumOfNodes(root);
            if(sum%2)
                return false;
            return checkValue(root->left, sum/2) || checkValue(root->right, sum/2);
        }
        
        int sumOfNodes(TreeNode* root)
        {
            if(root == NULL)
                return 0;
            return root->val + sumOfNodes(root->left)+sumOfNodes(root->right);
        }
        
        bool checkValue(TreeNode* node, int sum)
        {
            if(node == NULL)
                return false;
            if(sumOfNodes(node) == sum)
                return true;
            return checkValue(node->left, sum) || checkValue(node->right, sum);
        }
    };
    

Log in to reply
 

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