Problem Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Example Input
2 abc bac abdec dbeac
Example Output
abc abcde
01 | #include<stdio.h> |
02 | #include<stdlib.h> |
03 | #include<string.h> |
04 | char a[55], b[55]; |
05 | int flag; |
06 | struct node |
07 | { |
08 | char date; |
09 | struct node *l, *r; |
10 | }; |
11 | struct node *creat( int n, char a[], char b[]) |
12 | { |
13 | if (n == 0) return NULL; |
14 | struct node *root; |
15 | root = ( struct node *) malloc ( sizeof ( struct node)); |
16 | root->date = a[0]; |
17 | int i; |
18 | for (i = 0; i < n; i++) |
19 | { |
20 | if (a[0] == b[i]) |
21 | break ; |
22 | } |
23 | root->l = creat(i, a+1, b); |
24 | root->r = creat(n-1-i, a+i+1, b+1+i); |
25 | return root; |
26 | }; |
27 | void ceng( struct node *root) |
28 | { |
29 | int out = 0; |
30 | int in = 0; |
31 | struct node *p[10010]; |
32 | p[in++] = root; |
33 | while (out < in) |
34 | { |
35 | if (p[out]) |
36 | { |
37 | printf ( "%c" , p[out]->date); |
38 | p[in++] = p[out]->l; |
39 | p[in++] = p[out]->r; |
40 | } |
41 | out++; |
42 | } |
43 | } |
44 | int main() |
45 | { |
46 | int t, n; |
47 | scanf ( "%d" , &t); |
48 | while (t--) |
49 | { |
50 | scanf ( "%s%s" , a, b); |
51 | n = strlen (a); |
52 | struct node *root; |
53 | root = creat(n, a, b); |
54 | ceng(root); |
55 | printf ( "\n" ); |
56 | } |
57 | return 0; |
58 | } |
59 |