Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数
t (t<1000)
,代表有
t
行测试数据。每行是一个长度小于
50
个字符的字符串。
Output
输出二叉树的层次遍历序列。
Example Input
2 abd,,eg,,,cf,,, xnl,,i,,u,,
Example Output
abcdefg xnuli
01 | #include<stdio.h> |
02 | #include<stdlib.h> |
03 | #include<string.h> |
04 | char a[55]; |
05 | int flag; |
06 | struct node |
07 | { |
08 | char date; |
09 | struct node *l, *r; |
10 | }; |
11 | struct node *creat() |
12 | { |
13 | struct node *root; |
14 | if (a[++flag] == ',' ) |
15 | { |
16 | root = NULL; |
17 | } |
18 | else |
19 | { |
20 | root = ( struct node *) malloc ( sizeof ( struct node)); |
21 | root->date = a[flag]; |
22 | root->l = creat(); |
23 | root->r = creat(); |
24 | } |
25 | return root; |
26 | } |
27 | void ceng( struct node *root) |
28 | { |
29 | int out = 0; |
30 | int in = 0; |
31 | struct node *q[10010]; |
32 | q[in++] = root; |
33 | while (out < in) |
34 | { |
35 | if (q[out]) |
36 | { |
37 | printf ( "%c" , q[out]->date); |
38 | q[in++] = q[out]->l; |
39 | q[in++] = q[out]->r; |
40 | } |
41 | out++; |
42 | } |
43 | } |
44 | int main() |
45 | { |
46 | int t; |
47 | scanf ( "%d" , &t); |
48 | while (t--) |
49 | { |
50 | flag = -1; |
51 | scanf ( "%s" , a); |
52 | struct node *root; |
53 | root = creat(); |
54 | ceng(root); |
55 | printf ( "\n" ); |
56 | } |
57 | return 0; |
58 | } |