Last active
December 12, 2015 02:49
-
-
Save charlespunk/4702422 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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. |
This file contains hidden or 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 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