I don't understand why my code is wrong , is there any help?


  • 0
    P

    just like the title , my code as bellow:

    class Solution {
    public:
        bool isBalanced(TreeNode *root) {
            bool a=true;
            mybalance(root,a);
            return a;
        }
        int mybalance(TreeNode *root,bool& balance){
            if(root==NULL){
                balance = true;
                return 0;
            }
            if(balance==false)
               return 0;
            
            int left=mybalance(root->left,balance);
            int right=mybalance(root->right,balance);
            if(balance==false)
                return 0;
    
            if(-1<=left-right<=1){
                balance=true;
                if(left>=right)
                   return left+1;
                 else
                   return right+1;
            }
            else{
               balance=false;
               return 0;
            }
        }
    };

  • 0
    H

    See comments below:

    class Solution {
    public:
        bool isBalanced(TreeNode *root) {
            bool a=true;
            mybalance(root,a);
            return a;
        }
        int mybalance(TreeNode *root,bool& balance){
            if(root==NULL){
                balance = true; # delete this line. balance is a reference to a 'global' variable.
                # Your logic is to change it from true to false whenever an unbalanced subtree is detected. 
                # You should never change it back from false to true.
                return 0;
            }
            if(balance==false) 
               return 0;
    
            int left=mybalance(root->left,balance);
            int right=mybalance(root->right,balance);
            if(balance==false)
                return 0;
    
            if(-1<=left-right<=1){ # change to -1 <= left-right && left-right <= 1
                balance=true; # delete this line for the same reason given above
                if(left>=right)
                   return left+1;
                 else
                   return right+1;
            }
            else{
               balance=false;
               return 0;
            }
        }
    };

  • 0
    P

    oh thanks , it works , and thanks again to let me have a deeper understanding of this algorithm


Log in to reply
 

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