Created
August 23, 2013 05:34
-
-
Save charlespunk/6315852 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
Given a binary tree, determine if it is height-balanced. | |
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. |
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
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public boolean isBalanced(TreeNode root) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(check(root) == -1) return false; | |
else return true; | |
} | |
public int check(TreeNode root){ | |
if(root == null) return 0; | |
int left = check(root.left); | |
int right = check(root.right); | |
if(left == -1 || right == -1) return -1; | |
if(Math.abs(left - right) > 1) return -1; | |
return Math.max(left, right) + 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment