-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm1008.cpp
42 lines (36 loc) · 1.29 KB
/
m1008.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
/**
* 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* bstFromPreorder(vector<int>& preorder) {
TreeNode* root = new TreeNode(preorder[0]);
bstHelper(preorder, root, 1, INT_MIN, INT_MAX);
return root;
}
int bstHelper(vector<int>& preorder, TreeNode* curr, int indx, int lowerbound, int upperbound) {
if (indx >= preorder.size()) {
return indx;
}
if (lowerbound < preorder[indx] && preorder[indx] < curr->val) {
curr->left = new TreeNode(preorder[indx]);
indx = bstHelper(preorder, curr->left, indx + 1, lowerbound, curr->val);
}
if (indx >= preorder.size()) {
return indx;
}
if (preorder[indx] < upperbound && preorder[indx] > curr->val) {
curr->right = new TreeNode(preorder[indx]);
indx = bstHelper(preorder, curr->right, indx + 1, curr->val, upperbound);
}
return indx;
}
};