数据结构实验之求二叉树后序遍历和层次遍历

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值