Created
August 6, 2019 04:12
-
-
Save shixiaoyu/dcf37cce53e4d266d5f4d7d15214cce3 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
public boolean isBalanced(TreeNode root) { | |
return maxHeight(root) != -1; | |
} | |
// if -1, means it is not a balanced tree, since it will also return the normal height(int), so boolean is not an option. | |
// Kinda of a hack for the return type. | |
// @return -1 means it's already not a balanced tree, else t;he tree height | |
public int maxHeight(TreeNode root) { | |
if (root == null) { | |
return 0; | |
} | |
int l = maxHeight(root.left); | |
int r = maxHeight(root.right); | |
// a classic usage of post order traversalß | |
if (l == -1 || r == -1 || Math.abs(l - r) > 1) { | |
return -1; | |
} | |
return Math.max(l, r) + 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment