求树深度的递归算法

//求树深度的递归算法
int Depth(Bitree T)
{
if(!T) return 0;
else{
m=Depth(T->lchild); n=Depth(T->rchild); return (m>n?m:n)+1; }
}//Depth
//求二叉树中以值为x的结点为根的子树深度
int Get_Sub_Depth(Bitree T, int x)
{
if(T){
if(T->data==x)
return Depth(T);
//找到了值为x的结点,求x为根的子树的其深度
else{
if(T->lchild) m=Get_Sub_Depth(T->lchild,x); if(T->rchild) 

n=Get_Sub_Depth(T->rchild,x);
//在左右子树中继续寻找
}
return m>n?m:n;
}
return 0;
}//Get_Sub_Depth


//交换所有结点的左右子树
void Bitree_Revolute(Bitree T)
{
if(T){
T->lchild <=> T->rchild; //交换左右子树
if(T->lchild) Bitree_Revolute(T->lchild);
if(T->rchild) Bitree_Revolute(T->rchild);
}
}//Bitree_Revolute


//根据顺序存储结构建立二叉链表
Status CreateBitree_SqList(Bitree &T,SqList sa)
{
Bitree ptr[sa.last+1]; //该数组储存与sa中各结点对应的树指针 
if(!sa.last){
T=NULL; //空树
Return OK;
}
ptr[1]=(BTNode*)malloc(sizeof(BTNode));
ptr[1]->data=sa.elem[1]; //建立树根
T=ptr[1];
T->lchild=T->rchild=NULL;
for(i=2;i<=sa.last;i++){
if(!sa.elem[i]) return ERROR; //顺序错误
ptr[i]=(BTNode*)malloc(sizeof(BTNode));
ptr[i]->data=sa.elem[i];
ptr[i]->lchild= ptr[i]->rchild=NULL;
j=i/2; //找到结点i的双亲j
if(i==j*2) ptr[j]->lchild=ptr[i]; //i是j的左孩子
else if(i==2*j+1)ptr[j]->rchild=ptr[i]; //i是j的右孩子 }
return OK;
}//CreateBitree_SqList
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值