C语言 求一个二叉树中位于先序序列中第k个位置的结点的值
更新时间:2017/2/8 22:53:00 浏览量:786 手机版
编制一个递归算法,求一个二叉树中位于先序序列中第k个位置的结点的值
#include
#include
#define NULL 0
typedef char TElemType;
typedef struct BiNode
{ struct BiNode *lchild;
TElemType data;
struct BiNode *rchild;
}BiNode;
struct BiNode * CreateBiTree(struct BiNode *T)
{ TElemType a;
struct BiNode *t;
scanf("%c",&a);
if(a==' ') T=NULL;
else
{ t=(struct BiNode *)malloc(sizeof(BiNode));if(t!=NULL)
{ t->data=a;
T=t;
T->lchild=CreateBiTree(T->lchild);
T->rchild=CreateBiTree(T->rchild);
}
}
return T;
}
void show(struct BiNode *T)
{ if(T!=NULL)
{ printf("%c",T->data);
show(T->lchild);
show(T->rchild);
}
}
int tree(struct BiNode *T,int k,int a)
{ if(T==NULL)
{ a=a-1;
return a;
}
else
{ if(a==k)
{ printf("%c",T->data);
}
else
{ a=tree(T->lchild,k,a+1);
a=tree(T->rchild,k,a+1);
}
return a;
}
}
void main()
{ int i,k;
struct BiNode t;
struct BiNode *T;
T=&t;
printf("input elements of BiTree: "); T=CreateBiTree(T);
printf("\nthe BiTree is: ");
show(T);
printf("\ninput k: "); scanf("%d",&k);
printf("\nthe result is :");
tree(T,k,1);
}