If the tree is not balanced,just return -100. C++ 9ms


  • 0
    M
     class Solution {
     public:
    
     int findHigh(TreeNode* root)
     {
        if(!flag) return -100;
        int height=0;
        int lheight=0;
        int rheight=0;
        if(!root) return height;
        lheight=findHigh(root->left); 
        rheight=findHigh(root->right);
        if(lheight-rheight>1||rheight-lheight>1)
        {
               flag=false;
                return -100;
        }
        height=max(lheight,rheight)+1;
        return height;
     }
    
    bool isBalanced(TreeNode* root)
    {
        flag=true;
        findHigh(root);
        return flag;
    }
    
     private:
         bool flag;
    };

Log in to reply
 

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