Skip to content

Commit f0086e5

Browse files
committed
Adding leetcode solution recovering BST from preorder
1 parent ff3db55 commit f0086e5

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
TreeNode* constructBST(vector<int> preorder,int low,int high){
4+
if(low>=preorder.size() || low>high)
5+
return NULL;
6+
7+
TreeNode* root=new TreeNode(preorder[low]);
8+
if(high==low)
9+
return root;
10+
int i;
11+
for(i=low;i<=high;i++)
12+
if(preorder[i]>root->val)
13+
break;
14+
15+
root->left=constructBST(preorder,low+1,i-1);
16+
root->right=constructBST(preorder,i,high);
17+
return root;
18+
}
19+
20+
TreeNode* bstFromPreorder(vector<int>& preorder) {
21+
return constructBST(preorder,0,preorder.size()-1);
22+
}
23+
};

0 commit comments

Comments
 (0)