数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
输出
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linux xnuli
提示
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
char data;
struct node *l, *r;
};
struct node * creat(char *s1,char *s2, int len)
{
if(len <=0){
return NULL;
}
struct node *root;
root = (struct node *)malloc(sizeof(struct node));
root->data = *s1;
char *p;
for(p = s2;;p++){
if(*p == *s1){
break;
}
}
int k = p-s2;
root->l = creat(s1+1,s2,k);
root->r = creat(s1+k+1,p+1,len-k-1);
return root;
}
void three(struct node *tree)
{
if(tree){
three(tree->l);
three(tree->r);
printf("%c", tree->data);
}
}
void seque(struct node *tree)
{
struct node *q[100];
int head = 0;
int tail = 1;
q[head] = tree;
while(head < tail){
if(q[head]!=NULL){
printf("%c", q[head]->data);
q[tail++] = q[head]->l;
q[tail++] = q[head]->r;
}
head++;
}
}
int main()
{
int t;
while(~scanf("%d", &t)){
char s1[100];
char s2[100];
struct node *tree;
while(~scanf("%s %s", s1, s2)){
int len = strlen(s1);
tree = creat(s1,s2,len);
three(tree);
printf("\n");
seque(tree);
printf("\n");
}
}
return 0;
}