Skip to content

Commit 6a3bd7e

Browse files
authored
Create construct-binary-search-tree-from-preorder-traversal.cpp
1 parent 337b301 commit 6a3bd7e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
TreeNode* bstFromPreorder(vector<int>& preorder) {
16+
int index = 0;
17+
return bstFromPreorderHelper(preorder,
18+
numeric_limits<int>::min(),
19+
numeric_limits<int>::max(),
20+
&index);
21+
}
22+
23+
private:
24+
TreeNode* bstFromPreorderHelper(const vector<int>& preorder,
25+
int left,
26+
int right,
27+
int *index) {
28+
29+
if (*index == preorder.size() ||
30+
preorder[*index] < left ||
31+
preorder[*index] > right) {
32+
return nullptr;
33+
}
34+
35+
auto root = new TreeNode(preorder[(*index)++]);
36+
root->left = bstFromPreorderHelper(preorder, left, root->val, index);
37+
root->right = bstFromPreorderHelper(preorder, root->val, right, index);
38+
return root;
39+
}
40+
};

0 commit comments

Comments
 (0)