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);
}
判断一颗二叉树是否为平衡二叉树(AVL)
最新推荐文章于 2023-09-14 16:20:17 发布