Created
October 22, 2017 03:34
-
-
Save shailrshah/c00f6d1d8760c4a31007e353bd29d092 to your computer and use it in GitHub Desktop.
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public boolean isBalanced(TreeNode root) { | |
return getHeight(root) >= 0; | |
} | |
private int getHeight(TreeNode root) { | |
if(root == null) | |
return 0; | |
int leftHeight = getHeight(root.left); | |
if(leftHeight < 0) | |
return -1; | |
int rightHeight = getHeight(root.right); | |
if(rightHeight < 0) | |
return -1; | |
if(Math.abs(leftHeight - rightHeight) > 1) | |
return -1; | |
return Math.max(leftHeight + 1, rightHeight + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment