105. 从前序与中序遍历序列构造二叉树
为保证权益,题目请参考 105. 从前序与中序遍历序列构造二叉树(From LeetCode).
解决方案1
CPP
C++
/*
* LeetCode 105. 从前序与中序遍历序列构造二叉树
*
*/
#include <iostream>
#include <vector>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
return this->helper(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
}
TreeNode *helper(vector<int> &preorder, int pl, int pr, vector<int> &inorder, int il, int ir) {
if (pr - pl < 0) {
return nullptr;
}
//
auto *tmp = new TreeNode(preorder[pl]);
int i = 0;
for (i = il; i <= ir; i++) {
if (inorder[i] == preorder[pl]) {
break;
}
}
tmp->left = this->helper(preorder, pl + 1, pl + (i - il), inorder, il, i - 1);
tmp->right = this->helper(preorder, pl + (i - il) + 1, pr, inorder, i + 1, ir);
return tmp;
}
};
int main() {
vector<int> preorder;
preorder.push_back(3);
preorder.push_back(9);
preorder.push_back(20);
preorder.push_back(15);
preorder.push_back(7);
vector<int> inorder;
inorder.push_back(9);
inorder.push_back(3);
inorder.push_back(15);
inorder.push_back(20);
inorder.push_back(7);
Solution so;
so.buildTree(preorder, inorder);
return 0;
}
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78