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.
http://www.lintcode.com/submission/708408/
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.
bool isBalancedTree(TreeNode *root,int &depth) {
if(root == NULL) {
return true;
}
int leftDepth = 0;
bool leftResult = isBalancedTree(root->left, leftDepth);
if(!leftResult) {
return false;
}
int rightDepth = 0;
bool rightResult = isBalancedTree(root->right, rightDepth);
if(!rightResult) {
return false;
}
if(abs(leftDepth-rightDepth) >= 2) {
return false;
}
depth=(leftDepth>rightDepth)?(leftDepth+depth+1):(rightDepth+depth+1);
return true;
}
bool isBalanced(TreeNode *root) {
// write your code here
int depth=0;
return isBalancedTree(root ,depth);
}
balanced tree 满足三个条件:左右子树都是,高度差小于2
既要求高度又要加判断,所以必须用到引用
public:
int max(int i,int j) {
return i > j?i:j;
}
int getDepth(TreeNode *root) {
if (root == NULL) {
return 0;
}
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
if (leftDepth == -1 || rightDepth == -1 || abs(leftDepth-rightDepth) > 1) {
return -1;
}
return max(leftDepth,rightDepth) + 1;
}
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode *root) {
// write your code here
return getDepth(root) != -1;
}
用返回值是-1来给出子序列是否是balanced tree,更加巧妙
原文地址:http://blog.csdn.net/richard_rufeng/article/details/46641987