[LeetCode] Verify Preorder Sequence in Binary Search Tree

255. Verify Preorder Sequence in Binary Search Tree

Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool verifyPreorder(vector<int>& preorder) {
int l = INT_MIN;
vector<int> st;
for(auto& p : preorder) {
if(l > p) return false;
while(!st.empty() and st.back() < p) {
l = st.back(); st.pop_back();
}
st.push_back(p);
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/12/PS/LeetCode/verify-preorder-sequence-in-binary-search-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.