数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
Output
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。
Example Input
2 abdegcf dbgeafc xnliu lnixu
Example Output
dgebfca abcdefg linux xnuli
Hint
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
struct node*left,*right;
}tree;
char s1[55],s2[55];
tree*creat(char*s1,char*s2,int n)
{
int i;
if(n==0)
return NULL;
tree*root;
root=(tree*)malloc(sizeof(tree));
root->left=root->right=NULL;
root->data=s1[0];
for(i=0; i<n; i++)
{
if(s2[i]==root->data)
break;
}
root->left=creat(s1+1,s2,i);
root->right=creat(s1+1+i,s2+i+1,n-i-1);
return root;
}
void ans(tree*root)
{
queue<tree*>t;
if(root!=NULL)
t.push(root);
while(!t.empty())
{
root=t.front();
t.pop();
if(root)
{
printf("%c",root->data);
t.push(root->left);
t.push(root->right);
}
}
}
int main()
{
int nn,n;
while(scanf("%d",&nn)!=EOF)
{
getchar();
while(nn--)
{
tree*root=NULL;
scanf("%s",s1);
n=strlen(s1);
scanf("%s",s2);
root=creat(s1,s2,n);
last(root);
printf("\n");
ans(root);
printf("\n");
}
}
return 0;
}