-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-ConstructBinaryTree.cpp
More file actions
42 lines (33 loc) · 1.21 KB
/
Copy pathLeetCode-ConstructBinaryTree.cpp
File metadata and controls
42 lines (33 loc) · 1.21 KB
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
vector<int> m(6001, -1);
int n = inorder.size();
for (int i = 0; i < n; ++i) {
m[inorder[i] + 3000] = i;
}
return buildTree(preorder, inorder, m, 0, 0, preorder.size() - 1);
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder, vector<int>& m, int px, int l, int r) {
int n = preorder.size();
if (l > r) {
return nullptr;
}
TreeNode * root = new TreeNode(preorder[px]);
int x = m[root->val + 3000];
root->left = buildTree(preorder, inorder, m, px + 1, l, x - 1);
root->right = buildTree(preorder, inorder, m, px + 1 + (x - l), x + 1, r);
return root;
}
};