Created
December 19, 2014 14:24
-
-
Save wangchauyan/637aa5a03220b02fff67 to your computer and use it in GitHub Desktop.
Balance Tree Check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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