Verify Preorder Sequence in Binary Search Tree Problem
Description
LeetCode Problem 255.
Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.
Example 1:

Input: preorder = [5,2,1,3,6]
Output: true
Example 2:
Input: preorder = [5,2,6,1,3]
Output: false
Constraints:
1 <= preorder.length <= 10^41 <= preorder[i] <= 10^4- All the elements of
preorderare unique.
Follow up: Could you do it using only constant space complexity?
Solution
Approach: Monotonic Stack
In a preorder traversal we visit a node, then its whole left subtree, then its right subtree. While we are going down left, values decrease. When a value is larger than the last one, we have moved into the right subtree of some earlier node, and from then on every value must be larger than that node.
We keep a stack of nodes whose right subtree we have not entered yet; it is always decreasing from bottom to top. We also keep low, a lower bound for all remaining values. For each value x:
- If
x < low, it belongs to a left subtree we have already left, so the sequence is not a valid preorder: returnfalse. - Otherwise pop every stack value smaller than
x.xis in the right subtree of the last one popped, so that value becomes the newlow. - Push
x.
For [5,2,6,1,3]: after 6 we pop 2 and 5, so low = 5. Then 1 < 5 shows that 1 comes after we have already gone right of 5, which is impossible.
If we get through the whole array, a BST with this preorder exists.
Complexity: O(n) time, since each value is pushed and popped at most once, and O(n) space for the stack. (The follow-up's O(1) space version reuses the input array as the stack.)
class Solution:
def verifyPreorder(self, preorder: List[int]) -> bool:
stack = [] # nodes whose right subtree we have not entered yet (decreasing)
low = 0 # every value from now on must be greater than this (values are >= 1)
for x in preorder:
if x < low:
return False
# x is in the right subtree of every smaller node on the stack: leave their left subtrees.
while stack and stack[-1] < x:
low = stack.pop()
stack.append(x)
return True