Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created August 23, 2013 05:34
Show Gist options
  • Save charlespunk/6315852 to your computer and use it in GitHub Desktop.
Save charlespunk/6315852 to your computer and use it in GitHub Desktop.
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.
/**
* 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