http://www.lintcode.com/en/problem/balanced-binary-tree/ https://leetcode.com/problems/balanced-binary-tree/description/
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.
Example Given binary tree A = {3,9,20,#,#,15,7}, B = {3,#,20,15,7}
A) 3 B) 3
/ \ \
9 20 20
/ \ / \
15 7 15 7
The binary tree A is a height-balanced binary tree, but B is not.
解题 :要求平衡二叉树,所谓平衡二叉树就是叶子节点高度差不大于1。我们用分治法,遇到null时候返回0,然后比较左右子树高度差是不是大于1,当然也要看左右子树是不是-1,需要把-1冒泡到顶层去。
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
public boolean isBalanced(TreeNode root) {
// write your code here
int r = 0;
if(root != null) {
r = helper(root);
}
if(r == -1) {
return false;
}
return true;
}
public int helper(TreeNode node) {
if(node == null) {
return 0;
}
int leftDepth = helper(node.left);
int rightDepth = helper(node.right);
if(leftDepth == -1 || rightDepth == -1 || Math.abs(leftDepth - rightDepth) > 1) {
return -1;
}
return Math.max(leftDepth, rightDepth) + 1;
}
}