Skip to content

Instantly share code, notes, and snippets.

@jason51122
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jason51122/ec57311f8d1fcd8e9e41 to your computer and use it in GitHub Desktop.
Save jason51122/ec57311f8d1fcd8e9e41 to your computer and use it in GitHub Desktop.
4.1 Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return helper(root) != -1;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
if (left == -1) {
return -1;
}
int right = helper(root.right);
if (right == -1) {
return -1;
}
if (Math.abs(left - right) > 1) {
return -1;
}
else {
return Math.max(left, right) + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment