求二叉树的层次遍历

求二叉树的层次遍历

Description

已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。

Input

输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。

Output

每组输出这颗二叉树的层次遍历。

Sample

Input 

2
abc
bac
abdec
dbeac

Output 

abc
abcde
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 typedef struct node
 5 {
 6     char date;
 7     struct node *left;
 8     struct node *right;
 9 }tree;
10 tree *root,*link[54];
11 char str1[54],str2[54];
12 tree *get_build(int len,char *str1,char *str2)//建立二叉树
13 {
14     if(len==0)
15         return NULL;
16     int i;
17     tree *root;
18     root = (tree *)malloc(sizeof(tree));
19     root->date=str1[0];//寻找根节点,新的根节点为前序遍str1的第一个
20     for(i=0;i<len;i++)//寻找新的根节点在中序遍历str2中的位置
21     {
22         if(str2[i]==root->date)
23             break;
24     }
25     root->left = get_build(i,str1+1,str2);//左子树的长度,左子树在前序遍历中的开始位置,左子树在中序遍历中的开始位置
26     root->right = get_build(len-i-1,str1+i+1,str2+i+1);//右子树的长度,右子树在前序遍历中的位置,右子树在中序遍历的位置
27     return root;
28 }
29 void ans(tree *root)//二叉树的层序遍历
30 {
31     if(root)//判断root是否为NULL
32     {
33         int i=0,j=0;
34         link[j++]=root;
35         while(i<j)
36         {
37             if(link[i])
38             {
39                 link[j++]=link[i]->left;//入队
40                 link[j++]=link[i]->right;//入队
41                 printf("%c",link[i]->date);//层序遍历
42             }
43             i++;//出队
44         }
45     }
46 }
47 int main()
48 {
49     int t,len;
50     scanf("%d",&t);
51     while(t--)
52     {
53         scanf("%s %s",str1,str2);
54         len=strlen(str1);
55         root = get_build(len,str1,str2);//调用建立二叉树函数
56         ans(root);//调用二叉树的层序遍历函数
57         printf("
");
58  
59     }
60     return 0;
61 }
原文地址:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12722093.html