Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created August 6, 2019 04:12
Show Gist options
  • Save shixiaoyu/dcf37cce53e4d266d5f4d7d15214cce3 to your computer and use it in GitHub Desktop.
Save shixiaoyu/dcf37cce53e4d266d5f4d7d15214cce3 to your computer and use it in GitHub Desktop.
public boolean isBalanced(TreeNode root) {
return maxHeight(root) != -1;
}
// if -1, means it is not a balanced tree, since it will also return the normal height(int), so boolean is not an option.
// Kinda of a hack for the return type.
// @return -1 means it's already not a balanced tree, else t;he tree height
public int maxHeight(TreeNode root) {
if (root == null) {
return 0;
}
int l = maxHeight(root.left);
int r = maxHeight(root.right);
// a classic usage of post order traversalß
if (l == -1 || r == -1 || Math.abs(l - r) > 1) {
return -1;
}
return Math.max(l, r) + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment