C++ solution recursive


  • 0
    Z
    bool isBalanced(TreeNode* root) {
        if(root){
            int leftHeight = heightOfTree(root -> left);
            int rightHeight = heightOfTree(root -> right);
            if(abs(leftHeight - rightHeight) > 1){
                return false;
            }
            
            return (isBalanced(root -> left) && isBalanced(root -> right));
        }
        return true;
    }
    
    int heightOfTree(TreeNode* root){
        if(root){
            int heightL = 1;
            int heightR = 1;
            if(root -> left){
                heightL = heightOfTree(root -> left) + 1;
            }
            if(root -> right){
                heightR = heightOfTree(root -> right) + 1;
            }
            return heightL > heightR ? heightL : heightR;
        }
        return 0;
    }

Log in to reply
 

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