判断一颗二叉树是否为平衡二叉树(AVL)

struct BinaryTreeNode
{
	int data;
	struct BinaryTreeNode* pleft;
	struct BinaryTreeNode* pright;
};
//二叉树深度
int TreeDepth(BinaryTreeNode* root)
{
	if(root == NULL)
		return 0;
	int left = TreeDepth(root->pleft);
	int right = TreeDepth(root->pright);

	return (right > left ? right+1 : left+1);
}


//判断是否为平衡二叉树(AVL)
//效率较低,因为同一结点被重复遍历
//方法1:
bool IsBalanced(BinaryTreeNode* proot)
{
	if(proot == NULL)
		return true;

	int left = TreeDepth(proot->pleft);
	int right = TreeDepth(proot->pright);
	int diff = left - right;
	if(diff>1 || diff <-1)
		return false;

	return IsBalanced(proot->pleft) && IsBalanced(proot->pright);
}
//方法2:
//结点只遍历一次,较高效率
/*******************************************************
我们用后序遍历的方式遍历整棵二叉树。在遍历某结点的左右子结点
之后,我们可以根据它的左右子结点的深度判断它是不是平衡的,并
得到当前结点的深度。当最后遍历到树的根结点的时候,也就判断
了整棵二叉树是不是平衡二叉树。

********************************************************/
bool IsBalanced(BinaryTreeNode* proot, int *depth)
{
	if(proot == NULL)
	{
		*depth = 0;
		return true;
	}

	int left, right;
	if(IsBalaced(proot->pleft, &left) && IsBalanced(proot->pright, &right))
	{
		int diff = left - right;
		if(diff <=1 && diff >= -1)
		{
			*depth = 1 + left > right ? left : right;
			return true;
		}
		//return false;
	}
	return false;
}

bool IsBalanced(BinaryTreeNode* proot)
{
	int depth = 0;
	return IsBalanced(proot, &depth);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值