二叉树-----判断是否平衡二叉树

原理:二叉树每个结点的左右子树深度差不大于1时为平衡二叉树,只要在求二叉树的深度时判断深度差即可,采用递归方法

int TreeHeight(const TreeNode* root, bool& balanced)
{
//分别求出每个左右子树的深度
	const int LHeight = root->Left ? TreeHeight(root->Left) + 1 : 0;
	if (!balanced)
		return 0;
	const int RHeight = root->Right ? TreeHeight(root->Right) + 1 : 0;
	if (!balanced)
		return 0;
//保存每个结点的左右子树深度差
	const int diff = LHeight - RHeight;
//当深度差绝对值大于1时则不是平衡二叉树
	if (diff < -1 || diff>1)
		balanced = false;
	return (LHeight > RHeight ? LHeight : RHeight);
}

bool IsBalanced(const TreeNode* root)
{
	bool balanced = true;
	if (root)
		TreeHeight(root, balanced);
	return balanced;
}

猜你喜欢

转载自blog.csdn.net/weixin_39916039/article/details/81809269