-->
当前位置:首页 > 题库 > 正文内容

程序填空题:后序+中序创建二叉树

Luz4年前 (2021-05-10)题库1193
已知后序序遍历序列和中序遍历序列建立二叉树。
例如

![二叉树.png](~/91a62bfc-80cd-4a52-8e36-8a4689706e3b.png)


输入后序遍历序列:
FGDBCA,
再输入中序遍历序列:
BFDGAC,则
输出该二叉树的先序遍历序列:
ABDFGC。
```c++
#include
#include
#include
typedef char ElementType;
typedef struct BiTNode{
ElementType data;
struct BiTNode *lchild;
struct BiTNode *rchild;
}BiTNode,*BiTree;

BiTree CreatBinTree(char *post,char*in,int n);
void preorder( BiTree T );

int main()
{
BiTree T;
char postlist[100];
char inlist[100];
int length;
scanf("%s",postlist);
scanf("%s",inlist);
length=strlen(postlist);
T=CreatBinTree(postlist,inlist, length);
preorder( T );
return 0;
}
void preorder( BiTree T )
{
if(T)
{
printf("%c",T->data);
preorder(T->lchild);
preorder(T->rchild);

}
}
BiTree CreatBinTree(char *post,char*in,int n )
{
BiTree T;
int i;
if(n<=0) return NULL;
T=(BiTree)malloc(sizeof(BiTNode));
T->data=post[n-1];
for(i=0;in[i]!=post[n-1];i++);
T->lchild=@@[CreatBinTree(post,in,i)](3);
T->rchild=@@[CreatBinTree(post+i,in+i+1,n-i-1)](3);
return T;
}
```






答案:
第1空:CreatBinTree(post,in,i)

第2空:CreatBinTree(post+i,in+i+1,n-i-1)

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。