-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24 - Construct Binary Search Tree from Preorder Traversal.cpp
43 lines (40 loc) · 1.42 KB
/
24 - Construct Binary Search Tree from Preorder Traversal.cpp
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
/**
* 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* build_tree(vector<int>& preorder, vector <int> inorder, int In_start, int In_end, int &P_index, unordered_map <int, int> &mp){
if(In_start > In_end){
return NULL;
}
TreeNode* root = new TreeNode(preorder[P_index]);
int index = mp[preorder[P_index]];
P_index++;
root->left = build_tree(preorder,inorder,In_start,index-1,P_index,mp);
root->right = build_tree(preorder,inorder,index+1,In_end,P_index,mp);
return root;
}
TreeNode* bstFromPreorder(vector<int>& preorder) {
vector <int> preorder1 = preorder;
sort(preorder.begin(), preorder.end());
vector <int> inorder = preorder;
preorder = preorder1;
int In_start = 0;
int In_end = preorder.size() - 1;
int P_index = 0;
unordered_map <int, int> mp;
for(int i = 0; i<inorder.size(); i++){
mp[inorder[i]] = i;
}
TreeNode * res = build_tree(preorder,inorder,In_start,In_end,P_index,mp);
return res;
}
};