Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Sample
Input
2 abc bac abdec dbeac
Output
abc abcde
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char c;// 储存字符
struct node *lt, *rt;// 左右节点
};
char pre[50];// 前序
char in[50];// 中序
int len;
struct node *create(int len, char pre[], char in[]){/* 根据前序中序建立二叉树*/
struct node *root;
if(!len){// 如果长度为零,则不能建树
root = NULL;
return root;
}
root = (struct node *)malloc(sizeof(struct node));// 申请新的节点
root -> c = pre[0];// 前序的顺序第一个一定是根节点
int i;
for(i = 0; i < len; i++){// 寻找中序中到根节点,即现在的这颗树的所有左子树
if(pre[0] == in[i]){
break;// 找到跳出循环
}
}
root -> lt = create(i, pre + 1, in);// 建左子树
root -> rt = create(len - 1 - i, pre + 1 + i, in + 1 + i);// 建右子树
return root;// 返回根节点。
}
void hierarchical(struct node *root){/* 层次遍历*/
if(root){
int in = 0, out = 0;
struct node *hie[50];
hie[in++] = root;
while(out < in){
if(hie[out]){
printf("%c", hie[out] -> c);
hie[in++] = hie[out] -> lt;// 左子树
hie[in++] = hie[out] -> rt;// 右子树
}
out++;
}
}
}
int main(){
int t, i;
scanf("%d", &t);
for(i = 0; i < t; i++){
scanf("%s", pre);
scanf("%s", in);
len = strlen(pre);
struct node *root;
root = create(len, pre, in);
hierarchical(root);
printf("\n");
}
return 0;
}