#include<stdio.h>
#include<string.h>
struct Node
{
Node *lchild;
Node *rchild;
char c;
}Tree[50];
int loc; //记录节点个数
char str1[30],str2[30];
Node *Create()
{
Tree[loc].lchild=Tree[loc].rchild=NULL;
return &Tree[loc++];
}
void postOrder(Node *T)
{
if(T->lchild!=NULL)
postOrder(T->lchild);
if(T->rchild!=NULL)
postOrder(T->rchild);
printf("%c ",T->c);
}
Node *build(int s1,int e1,int s2,int e2)
{
Node *ret = Create();
ret->c=str1[s1];
int idx=0,i;
for(i=s2;i<=e2;++i)
{
if(str1[s1]==str2[i])
{
idx=i;
break;
}
}
if(idx!=s2)
ret->lchild=build(s1+1,s1+(idx-s2),s2,idx-1);
if(idx!=e2)
ret->rchild=build(s1+(idx-s2)+1,e1,idx+1,e2);
return ret;
}
int main()
{
while(scanf("%s",str1)!=EOF)
{
scanf("%s",str2);
loc=0;
int L1=strlen(str1);
int L2=strlen(str2);
Node *T=build(0,L1-1,0,L2-1);
postOrder(T);
printf("\n");
}
return 0;
}
建立二叉树(已知中序遍历和先序遍历)
最新推荐文章于 2021-07-10 19:53:50 发布