[Geeks for Geeks] Preorder Traversal and BST

Preorder Traversal and BST

Given an array arr[ ] of size N consisting of distinct integers, write a program that returns 1 if given array can represent preorder traversal of a possible BST, else returns 0.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int canRepresentBST(int arr[], int N) {
int pos = 0, mi = INT_MIN, ma = INT_MAX;
vector<pair<int,int>> st;
st.push_back({mi, ma});
while(!st.empty() and pos < N) {
auto p = st.back(); st.pop_back();
if(p.first < arr[pos] and arr[pos] < p.second) {
st.push_back({arr[pos], p.second});
st.push_back({p.first, arr[pos]});
pos++;
}
}
return pos >= N;
}
};

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