12ms easy understand C++


  • -3
    V
    class Solution {
    public:
        bool isBalanced(TreeNode* root) {
            if(!root) return true;
            if(!root->left && !root->right)
            {   root->val=1; return true; }
    
    
            if(!isBalanced(root->left) || !isBalanced(root->right))
                return false;
    
            int left=0, right=0;
            if(root->left)
                left=root->left->val;
            if(root->right)
                right=root->right->val;
    
            if(abs(left-right)>1)
                return false;
    
            root->val=max(left,right)+1;
            return true;
        }
    };

  • 0

    I thought val could not be modified.


  • 0
    B

    I agree with that. I believe it is one of basic principle to solve the problem.
    The tree which val is changed could not be useful and valid for its propose in reality, so we lost the meaning of this solution


Log in to reply
 

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