判断二叉数是否是平衡树

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;
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值