已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输出
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linux xnuli
Memory: 272 KB | Time: 0 MS | |
Language: g++ | Result: Accept |
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char a[1000],b[1000];
struct node
{
char data;
struct node *l,*r;
};
struct node *build(char *a,char *b,int n)
{
if(n<=0)
{
return NULL;
}
char x = a[0];///找到根节点
struct node *t;
t = (struct node *)malloc(sizeof(struct node ));
t->data = x;
int i;
for(i=0;i<n;i++)
{
if(b[i] == x)///排除重复遍历
break;
}
t->l = build(a+1,b,i);///右子树+1
t->r = build(a+i+1,b+i+1,n-i-1);
return t;
}
void last(struct node *t)///后序遍历
{
if(t!=NULL)
{
last(t->l);
last(t->r);
printf("%c",t->data);
}
}
void add(struct node *t)///层次遍历
{
struct node *f[1000];
int in=1,out=0;
f[0] = t;
while(in>out)///队列不为空
{
if(f[out])//一次遍利一层 将一层的所有子树加进队列
{
printf("%c",f[out]->data);
f[in] = f[out]->l;//左孩子进列
in++;
f[in] = f[out]->r;//有孩子进列
in++;
out++;
}
else
out++;
}
}
/*void cengci(struct node *r)
{
struct node *p;
struct node *qu[N];//定义环形队列,存放结点指针
int head,wei;//定义队头,队尾指针
head= wei =-1;//队列初始化为空
wei ++;
qu[wei ]=r;//根节点指针进入队列
while(head != wei )//队列不为空时
{
head = (head+1)%N;
p=qu[head]; //队头元素出列
printf("%c",p->data);//访问结点 if(p->left != NULL)
{
wei = (wei + 1) % N; //有左孩子时将其进队
qu[wei] = p->left;
} if(p->right!=NULL)
{
wei=(wei + 1)%N;//有右孩子时将其进队
qu[wei]=p->right;
}
}
}*/
int main()
{ int m;
struct node *tree;
while(~scanf("%d",&m))
{
while(m--)
{
scanf("%s%s",a,b);
int len = strlen (a);
tree = build(a,b,len);
last(tree);
printf("\n");
add(tree);
printf("\n");
}
}
return 0;
}