2ms Java solution


  • 2
    Y
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            // 1:20pm - 1:33pm
            return height(root) != -1;
        }
        
        private int height(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int leftHeight = height(root.left);
            if (leftHeight == -1) {
                return -1;
            }
            int rightHeight = height(root.right);
            if (rightHeight == -1) {
                return -1;
            }
            if (Math.abs(leftHeight - rightHeight) > 1) {
                return -1;
            }
            return 1 + Math.max(leftHeight, rightHeight);
        }
    }

Log in to reply
 

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