计算二叉树中每个节点的平衡因子

时间:2025-04-15 07:39:05

思想:递归的计算每个节点的左子树与右子树的深度,然后左子树深度-右子树深度即为平衡因子

int Depth(BiTree T)
{
int l=0,r=0;
int *p;
p=T;          //p指向当前树T
if(p==NULL)
  return 0;
else
{
l=Depth(p->lchild);      //遍历左子树
r=Depth(p->rchild);        //遍历右子树
return (l>r?l:r)+1;       //左子树与右子树个数多的为当前树的深度
}
}
int bf(BiTree &T)
{
int LNum,RNum;     //记录左右子树的度
if(T)
{
 bf(T->lchild);       //从树的底部开始计算
 bf(T->rchild):
 LNum=Depth(T->lchild);      //当前节点左子树的度
 RNum=Depth(T->rchild);  //当前节点右子树的度
 T->bf=LNum-RNum;     //当前节点的平衡因子
}
}