An easy understanding solution


  • 0
    S
    bool isBalanced(TreeNode *root){
        bool flag = true;
        depth(root, flag);
        return flag;
    }
    
    int depth(TreeNode *root, bool &flag){
        if(!flag || (NULL == root)) return 0;
        
        int lh = depth(root->left, flag);
        if(!flag) return 0;
        
        int rh = depth(root->right, flag);
        if(!flag) return 0;
        
        flag = abs(lh-rh) <= 1;
        return max(lh, rh) + 1;
    }

  • 0
    J

    there is no need to pass flag in each call. just return -1 if not balanced.


  • 0
    S

    you are right, that's better


Log in to reply
 

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