Recursive solution. Java.


  • 0
    O
        public boolean isBalanced(TreeNode root) {
            if(root == null) {
                return true;
            }
            boolean isBalanced = true;
            if (root.left != null) {
                isBalanced = isBalanced(root.left);
            }
            if (root.right != null && isBalanced) {
                isBalanced = isBalanced(root.right);
            }
            if (!isBalanced) {
                return false;
            }
            int hLeft = 0, hRight = 0;
            hLeft  = getHeight(root.left)  + 1;
            hRight = getHeight(root.right) + 1;
            
            return Math.abs(hLeft-hRight) <= 1 ? true : false;
        }
        
        public int getHeight(TreeNode root) {
            if (root == null) {
                return 0;
            }
            
            int hLeft = 0, hRight = 0;
            hLeft  = getHeight(root.left)  + 1;
            hRight = getHeight(root.right) + 1;
            
            return Math.max(hLeft, hRight);
        }
    ```>! Spoiler

Log in to reply
 

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