[AlgoExpert] Reconstruct BST

Reconstruct BST

  • Time : O(n)
  • Space : O(n)
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
using namespace std;

// This is an input class. Do not edit.
class BST {
public:
int value;
BST *left = nullptr;
BST *right = nullptr;

BST(int value) { this->value = value; }
};

BST* helper(vector<int>& A, int& pos, int mi, int ma) {
if(pos == A.size()) return nullptr;
if(mi <= A[pos] and A[pos] < ma) {
BST* bst = new BST(A[pos++]);
bst->left = helper(A,pos,mi,bst->value);
bst->right = helper(A,pos,bst->value,ma);
return bst;
} else return nullptr;
}

BST *reconstructBst(vector<int> preOrderTraversalValues) {
int pos = 0;
return helper(preOrderTraversalValues, pos, INT_MIN, INT_MAX);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/AlgoExpert/reconstruct-bst/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.