Skip to content

Commit 5115781

Browse files
Create Day 24 Construct Binary Search Tree from Preorder Traversal.cpp
1 parent 5f607cb commit 5115781

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
PROBLEM:
2+
3+
4+
5+
Return the root node of a binary search tree that matches the given preorder traversal.
6+
7+
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val,
8+
and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the
9+
node first, then traverses node.left, then traverses node.right.)
10+
11+
It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.
12+
13+
Example 1:
14+
15+
Input: [8,5,1,7,10,12]
16+
Output: [8,5,10,1,7,null,12]
17+
18+
19+
20+
21+
SOLUTION:
22+
23+
24+
25+
/**
26+
* Definition for a binary tree node.
27+
* struct TreeNode {
28+
* int val;
29+
* TreeNode *left;
30+
* TreeNode *right;
31+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
32+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
33+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
34+
* };
35+
*/
36+
class Solution {
37+
public:
38+
TreeNode* bstFromPreorder(vector<int>& preorder) {
39+
int i=0;
40+
return bst(preorder,INT_MAX,i);
41+
42+
}
43+
44+
TreeNode* bst(vector<int>& preorder,int upper,int &i)
45+
{
46+
if(i==preorder.size() || preorder[i] > upper)
47+
return NULL;
48+
49+
TreeNode* newnode = new TreeNode(preorder[i]);
50+
i++;
51+
newnode->left = bst(preorder,newnode->val,i);
52+
newnode->right = bst(preorder,upper,i);
53+
54+
return newnode;
55+
}
56+
};

0 commit comments

Comments
 (0)