求树深度的递归算法

来源:互联网 发布:php鲜花网模板源码 编辑:程序博客网 时间:2024/06/15 00:03
//求树深度的递归算法
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