求二叉树的层次遍历

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(structnode));
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  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值