18.11.02 由中根序列和后根序列重建二叉树-数据结构习题

题目内容:

我们知道如何按照三种深度优先次序来周游一棵二叉树,来得到中根序列、前根序列和后根序列。反过来,如果给定二叉树的中根序列和后根序列,或者给定中根序列和前根序列,可以重建一二叉树。本题输入一棵二叉树的中根序列和后根序列,要求在内存中重建二叉树,最后输出这棵二叉树的前根序列。

用不同的整数来唯一标识二叉树的每一个结点,下面的二叉树

 

中根序列是9 5 32 67

后根序列9 32 67 5

前根序列5 9 67 32

 

 

 

输入格式:

两行。第一行是二叉树的中根序列,第二行是后根序列。每个数字表示的结点之间用空格隔开。结点数字范围0~65535。暂不必考虑不合理的输入数据。

 

输出格式:

一行。由输入中的中根序列和后根序列重建的二叉树的前根序列。每个数字表示的结点之间用空格隔开。

 

输入样例:

9 5 32 67
9 32 67 5

 

输出样例:

5 9 67 32

 

时间限制:500ms内存限制:32000kb
 1 #include <iostream>
 2 #include <string.h>
 3 #include <algorithm>
 4 #include <stack>
 5 #include <string>
 6 #include <math.h>
 7 #include <queue>
 8 #include <stdio.h>
 9 #include <string.h>
10 #include <vector>
11 #include <fstream>
12 #include <set>
13 
14 using namespace std;
15 int mid[65536], back[65536];
16 int count0 = 0;//计结点个数数
17 bool flag;//是否是第一次输出
18 
19 void init() {
20     int i = 0;
21     scanf("%d", &mid[++i]);
22     while (getchar() != '\n')//当读入一个换行符就说明一行读完
23         scanf("%d", &mid[++i]);
24     count0 = i;
25     for (int i = 1; i <= count0; i++)
26         scanf("%d", &back[i]);
27 }
28 
29 void front(int mids, int mide, int backs, int backe) {
30     if (mids > mide )return;
31     if (flag) {
32         printf("%d", back[backe]);
33         flag = false;
34     }
35     else
36         printf(" %d", back[backe]);
37     int spot = find(mid+mids,mid+mide+1, back[backe])-mid;
38     int lft = spot - mids;
39     front(mids, spot - 1, backs, backs + lft - 1);//递归输出左子树的根节点
40     front(spot + 1, mide, backs + lft, backe-1);//递归输出右子树的根节点
41 }
42 
43 int main()
44 {
45     flag = true;
46     init();
47     front(1, count0, 1, count0);
48     return 0;
49 }
View Code

今天做题太玄学了

这题一开始想着这个OJ的数据按以往经验非常水所以直接递归吧

居然TLE

然后换栈

依然TLE??

最后发现好像是输入里有问题,但我至今还没明白为啥,就是将本来后序数组也用getchar判断输入的,改成了数元素个数输入,然后就过了

难道是题目数据里面最后没有换行符???

今天貌似只要做题就不顺,不如回家打游戏吧

猜你喜欢

转载自www.cnblogs.com/yalphait/p/9898335.html