[InterviewBit] Construct BST from Preorder

Construct BST from Preorder

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
TreeNode* dfs(vector<int>& A, int& p, int mi, int ma) {
if(p >= A.size()) return NULL;
if(mi < A[p] and A[p] < ma) {
TreeNode* res = new TreeNode(A[p++]);
res->left = dfs(A,p,mi,res->val);
res->right = dfs(A,p,res->val,ma);
return res;
}
return NULL;
}
TreeNode* Solution::constructBST(vector<int> &A) {
int p = 0;
return dfs(A,p, INT_MIN, INT_MAX);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/15/PS/interviewbit/construct-bst-from-preorder/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.