reConstructBinaryTree

问题:输入某二叉树的前序遍历和中序遍历的结果,重建二叉树,假设前序遍历和中序遍历的结果中都不包含重复的数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <vector>
using namespace std;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
TreeNode *build(vector<int> &pre, int p_l, int p_r, vector<int> &vin, int v_l, int v_r) {
// 找到pre[p_l]在vim中的位置
TreeNode *cur = new TreeNode(pre[p_l]);
if (p_l == p_r) {
return cur;
}
int count = 0;
for (int i = v_l; i <= v_r; i++) {
if (vin[i] == pre[p_l]) {
count = i - v_l;
}
}
//
if (count == 0) {
cur->right = build(pre, p_l + 1, p_r, vin, v_l + 1, v_r);
} else if (v_l + count == v_r) {
cur->left = build(pre, p_l + 1, p_r, vin, v_l, v_r - 1);
} else {
cur->left = build(pre, p_l + 1, p_l + count, vin, v_l, v_l + count - 1);
cur->right = build(pre, p_l + count + 1, p_r, vin, v_l + count + 1, v_r);
}
return cur;
}

TreeNode *reConstructBinaryTree(vector<int> pre, vector<int> vin) {
TreeNode *root = build(pre, 0, pre.size() - 1, vin, 0, vin.size() - 1);
return root;
}
};

int main() {
vector<int> pre = {1, 2, 4, 7, 3, 5, 6, 8};
vector<int> vin = {4, 7, 2, 1, 5, 3, 8, 6};
Solution solution;
TreeNode *root = solution.reConstructBinaryTree(pre, vin);
return 0;
}