已知二叉树的前序遍历和中序遍历求整颗二叉树
实现代码:
1 #include<iostream>
2 #include<cstdio>
3 #include<algorithm>
4 #include<vector>
5 #include<map>
6 #include<queue>
7 #include<set>
8 #include<cmath>
9 #include<list>
10 #include<cstring>
11 #include<string>
12 #define ll long long
13 #define ull unsigned long long
14 #define inf 0x3f3f3f3f
15 #define inff 0x7fffffff
16 using namespace std;
17 const int N = 10000 + 10;
18 const int M = 200000 + 10;
19 const int mod = 1e9 + 7;
20
21 int pre[N], in[N];
22
23 typedef struct node* BinTree;
24
25 struct node {
26 int date;
27 BinTree left;
28 BinTree right;
29 };
30
31 BinTree Build(int pre[], int in[], int size) {
32
33 if (size <= 0) return NULL;
34 int rem = 0;
35 for (int i = 0; i < size; i++) {
36 if (in[i] == pre[0]) {
37 rem = i;
38 break;
39 }
40 }
41 BinTree tree = (BinTree)malloc(sizeof(struct node));
42 tree->date = pre[0];
43 tree->left = Build(pre + 1, in, rem);
44 tree->right = Build(pre + rem + 1, in + rem + 1, size - rem - 1);
45
46 return tree;
47 }
48
49 void postorder(BinTree T) {
50
51 if (T == NULL) return;
52 else {
53 postorder(T->left);
54 postorder(T->right);
55 cout << T->date << " ";
56 }
57
58 return;
59 }
60
61 int main() {
62
63 int n;
64 cin >> n;
65 for (int i = 0; i < n; i++) {
66 cin >> pre[i];
67 }
68 for (int i = 0; i < n; i++) {
69 cin >> in[i];
70 }
71 BinTree T;
72 T = Build(pre, in, n);
73 postorder(T);
74
75 return 0;
76 }
永远热爱,永远向着光。

浙公网安备 33010602011771号