数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
Output
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。
Sample Input
2 abdegcf dbgeafc xnliu lnixuSample Output
dgebfca abcdefg linux xnuli
#include <stdio.h>
#include <stdlib.h>
char s[1500];
int i;
typedef struct
{
char data;
struct tree *Lchild;
struct tree *Rchild;
}tree;
struct tree * pai(char *xian, char *zhong, int len)
{
if(len == 0)
return NULL;
tree *temp = (tree *)malloc(sizeof(tree));
temp -> data = *xian;
int i;
for(i=0;i<len;i++)
{
if(zhong[i]==*xian)
{
break;
}
}
temp -> Lchild = pai(xian+1, zhong, i);
temp -> Rchild = pai(xian+i+1, zhong+i+1,len-i-1);
return temp;
};
levelshow(tree *head)
{
tree *temp[100];
int front=0, rear=-1;
temp[++rear] = head;
while(rear>=front)
{
if(temp[front])
{
printf("%c", temp[front]->data);
temp[++rear] = temp[front]->Lchild;
temp[++rear] = temp[front]->Rchild;
}
front++;
}
}
postshow(tree *temp)
{
if(temp)
{
postshow(temp->Lchild);
postshow(temp->Rchild);
printf("%c", temp->data);
}
}
int main()
{
char zhong[100], xian[100];
int i, len;
tree *head;
int n;
scanf("%d", &n);
while(n--)
{
scanf("%s", xian);
scanf("%s", zhong);
len = strlen(zhong);
head = pai(xian, zhong, len);//建树
postshow(head);
printf("\n");
levelshow(head);//层次遍历
printf("\n");
}
return 0;
}