-
-
Save jason51122/ec57311f8d1fcd8e9e41 to your computer and use it in GitHub Desktop.
4.1 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 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) { | |
if (root == null) { | |
return true; | |
} | |
return helper(root) != -1; | |
} | |
private int helper(TreeNode root) { | |
if (root == null) { | |
return 0; | |
} | |
int left = helper(root.left); | |
if (left == -1) { | |
return -1; | |
} | |
int right = helper(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