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.
Solutions:
可以写一个函数求一棵二叉树的深度。每次判断一个节点时就将分别求其左右子树的深度,深度相减判断。
<pre name="code" class="cpp">int getHeight(TreeNode *root) {
if(root == NULL){
return 0;
}
int l=getHeight(root->left);
int r=getHeight(root->right);
return 1 + (l>r?l:r);
}
但这样明显有重复运算。
可以边计算深度边判断。
class Solution {
public:
bool judgeBalance(TreeNode *root, int &height) {
if(root == NULL) {
height=0;
return true;
}
int rh=0, lh=0;
bool l=judgeBalance(root->left, lh);
bool r=judgeBalance(root->right, rh);
if(l && r) {
if(rh-lh<-1 || rh-lh >1) {
return false;
}
height=1+ (rh>lh?rh:lh);
}
else {
return false;
}
}
bool isBalanced(TreeNode* root) {
int h=0;
return judgeBalance(root, h);
}
};
转自http://blog.sina.com.cn/s/blog_819d2f490100sz7e.html的方法:
我们再回过头看平衡二叉树的定义,即平衡二叉树需要满足的条件:(1)空树:depth = 0
(2)不为空树,左右子树都为平衡二叉树,且左右子树高度差的绝对值小于等于1
我们是不是可以用高度来判断一棵二叉树是不是平衡二叉树呢?
如果高度 >= 0,则是平衡二叉树;
如果高度 < 0,则不是平衡二叉树。
class Solution {
public:
int isBalanced(TreeNode *root) {
if(root == NULL) {
return 0;
}
int l=isBalanced(root->left);
int r=isBalanced(root->right);
if(l >= 0 && r>=0) {
if(l-r <= -1 || l-r >= 1) {
return l>=r?(l+1):(r+1);
}
}
return -1;
}
};