Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 12, 2015 02:49
Show Gist options
  • Save charlespunk/4702422 to your computer and use it in GitHub Desktop.
Save charlespunk/4702422 to your computer and use it in GitHub Desktop.
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 static boolean isBalanced(Node root){
boolean is = false;
if(check(root) > -1) is = true;
return is;
}
public int check(root){
if(root == null) return 0;
int left = check(root.left);
if(left == -1) return -1;
int right = check(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