数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
Output
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。
Sample Input
2 abdegcf dbgeafc xnliu lnixu
Sample Output
dgebfca abcdefg linux xnuli
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char num;
struct node *l,*r;
};
struct node *kk(char i[],int n,char j[])
{
if(n<=0)
return NULL;
struct node *root;
root=(struct node *)malloc(sizeof(struct node));
root->num=i[0];
int v;
for(v=0;v<n;v++)
if(i[0]==j[v])break;
root->l=kk(i+1,v,j);
root->r=kk(i+v+1,n-v-1,j+v+1);
return root;
};
void gg(struct node *root)
{
if(root==NULL)
return ;
gg(root->l);
gg(root->r);
printf("%c",root->num);
}
void zz(struct node *t)
{
if(t==NULL)
return ;
int f=1,i=1;
struct node *s[1000],*q;
s[1]=t;
while(f<=i)
{
q=s[f++];
printf("%c",q->num);
if(q->l!=NULL)
{
s[++i]=q->l;
}
if(q->r!=NULL)
{
s[++i]=q->r;
}
}
}
int main()
{
int a,b;
char i[1000],j[1000];
struct node *root,*t;
scanf("%d",&a);
while(a--)
{
scanf("%s %s",i,j);
b=strlen(i);
root=kk(i,b,j);
t=root;
gg(root);
printf("\n");
zz(t);
printf("\n");
}
return 0;
}