Skip to content

Instantly share code, notes, and snippets.

@wangchauyan
Created December 19, 2014 14:24
Show Gist options
  • Save wangchauyan/637aa5a03220b02fff67 to your computer and use it in GitHub Desktop.
Save wangchauyan/637aa5a03220b02fff67 to your computer and use it in GitHub Desktop.
Balance Tree Check
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
if(checkHeight(root) == -1) return false;
else return true;
}
int checkHeight(TreeNode node) {
if(node == null) return 0;
int leftHeight = checkHeight(node.left);
if(leftHeight == -1) return -1;
int rightHeight = checkHeight(node.right);
if(rightHeight == -1) return -1;
if(Math.abs(leftHeight - rightHeight) > 1) return -1;
else return Math.max(leftHeight, rightHeight) + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment