Problem Description
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
Output
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。
Example Input
2 abdegcf dbgeafc xnliu lnixu
Example Output
dgebfca abcdefg linux xnuli
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 last( struct node *root) |
28 | { |
29 | if (root) |
30 | { |
31 | last(root->l); |
32 | last(root->r); |
33 | printf ( "%c" , root->date); |
34 | } |
35 | } |
36 | void ceng( struct node *root) |
37 | { |
38 | int out = 0; |
39 | int in = 0; |
40 | struct node *p[10010]; |
41 | p[in++] = root; |
42 | while (out < in) |
43 | { |
44 | if (p[out]) |
45 | { |
46 | printf ( "%c" , p[out]->date); |
47 | p[in++] = p[out]->l; |
48 | p[in++] = p[out]->r; |
49 | } |
50 | out++; |
51 | } |
52 | } |
53 | int main() |
54 | { |
55 | int t, n; |
56 | scanf ( "%d" , &t); |
57 | while (t--) |
58 | { |
59 | scanf ( "%s%s" , a, b); |
60 | n = strlen (a); |
61 | struct node *root; |
62 | root = creat(n, a, b); |
63 | last(root); |
64 | printf ( "\n" ); |
65 | ceng(root); |
66 | printf ( "\n" ); |
67 | } |
68 | return 0; |
69 | } |
70 |