Balanced Binary Tree
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.
the tree is only balanced if:
- The left and right subtrees' heights differ by at most one, AND
- The left subtree is balanced, AND
- The right subtree is balanced
so tree like this is also balanced:
o
/ \
o o
/ / \
o o o
/
o
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isBalanced(TreeNode root) { 12 // IMPORTANT: Please reset any member data you declared, as 13 // the same Solution instance will be reused for each test case. 14 return (check(root) != -1); 15 } 16 public int check(TreeNode node){ 17 if(node == null) return 0; 18 else{ 19 int left = check(node.left); 20 if(left == -1) return -1; 21 int right = check(node.right); 22 if(right == -1) return -1; 23 if(Math.abs(left - right) < 2) return (left > right ? left : right) + 1; 24 else return -1; 25 } 26 } 27 }
posted on 2013-09-12 14:28 Step-BY-Step 阅读(173) 评论(0) 编辑 收藏 举报