数据结构实验之求二叉树后序遍历和层次遍历
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
Hint
Source
ma6174
注在VJ上提交这个代码记得选择 C++提交,要不然会报错。弱弱的我也不清楚怎么回事。。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node
{
char data;
struct node *left;
struct node *right;
}tree;
char str1[54],str2[54];
tree *root,*link[54];
tree *get_build(int len,char *str1,char *str2)
{
if(len==0)
return NULL;
int i;
tree *root;
root=(tree *)malloc(sizeof(tree));
root->data=str1[0];
for(i=0;i<len;i++)
{
if(str2[i]==root->data)
break;
}
root->left=get_build(i,str1+1,str2);
root->right=get_build(len-i-1,str1+i+1,str2+i+1);
return root;
}
void ans(tree *root)//层序遍历序列
{
if (root)
{
int i=0,j=0;
link[j++]=root;
while(i<j)
{
if(link[i])
{
link[j++]=link[i]->left;
link[j++]=link[i]->right;
printf("%c",link[i]->data);
}
i++;
}
}
}
void post(tree *root)//后序遍历序列
{
if (root)
{
post(root->left);
post(root->right);
printf("%c",root->data);
}
}
int main()
{
int t,len;
scanf("%d",&t);
while(t--)
{
scanf("%s %s",str1,str2);
len=strlen(str1);
root=get_build(len,str1,str2);
post(root);
printf("\n");
ans(root);
printf("\n");
}
return 0;
}