判断是不是平衡二叉树

问题:给出一棵二叉树,判断它是不是二叉树。

一个比较容易想到的做法是,采用动态规则的方法依次求出每一个节点的左子树深度和右子树深度,两者相减,绝对值大于 1 则不是平衡树。为了避免重复计算节点的深度,应该用后序遍历的方法,即先计算子节点的深度,再计算当前节点的深度,这样不会出现重复计算。

代码如下:

struct Tree
{
	Tree *left,*right;
	int value;
};

static const int MAX_BALANCE_DIFF = 1;
static const int INT_SIZE = 8 * sizeof(int);//当前计算机中一个 int 占几个字节

int fastAbs(int n)
{
	
	return (n ^ (n >> (INT_SIZE - 1))) - (n >> (INT_SIZE - 1));// 见http://blog.youkuaiyun.com/lizhihaoweiwei/article/details/37757901
}

int max(int a,int b)
{
	return a >= b ? a : b;
}

int treeDepth(const Tree *theTree,bool * const isBalance)
{
	if(!*isBalance)
	{
		return 0;
	}
	if(NULL == theTree)
	{
		return 0;
	}
	Tree *left = theTree->left;
	Tree *right = theTree->right;
	int leftDepth = 0,rightDepth = 0;

	leftDepth = treeDepth(left,isBalance);
	rightDepth= treeDepth(right,isBalance);
	if(MAX_BALANCE_DIFF < fastAbs(leftDepth - rightDepth))
	{
		*isBalance = false;
	}
	return 1 + max(leftDepth,rightDepth);
}

bool isBanlaceTree(const Tree *theTree)
{
	bool isBalance = true;
	treeDepth(theTree,&isBalance);
	return isBalance;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值