Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created October 22, 2017 03:34
Show Gist options
  • Save shailrshah/c00f6d1d8760c4a31007e353bd29d092 to your computer and use it in GitHub Desktop.
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.
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