255. Verify Preorder Sequence in Binary Search Tree
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to validate if a given array of unique integers represents a valid preorder traversal of a Binary Search Tree (BST).
Solution
Verify Preorder Sequence in Binary Search Tree in Python
class Solution:
def verifyPreorder(self, preorder: List[int]) -> bool:
# lower_bound stores the value of the parent node whose right subtree
# we are currently traversing. Any subsequent node must be greater than this.
lower_bound = float('-inf')
# Use a list as a stack to store parent nodes.
stack = []
for p in preorder:
# If we find a node that is smaller than the lower_bound, it's a violation.
# This means a node in a right subtree is smaller than its grandparent-like ancestor.
if p < lower_bound:
return False
# While the current node `p` is greater than the top of our stack,
# it means we are moving to the right subtree. The popped nodes are
# roots of subtrees whose left branches are fully traversed.
while stack and p > stack[-1]:
# The popped node becomes the new lower bound.
lower_bound = stack.pop()
# Push the current node onto our stack.
stack.append(p)
return True
# Note: While the problem has a follow-up for an O(1) space solution which modifies the input array,
# the O(N) space solution is cleaner and often preferred if input modification is disallowed.
# Here is the O(1) space solution for completeness:
#
# class Solution:
# def verifyPreorder(self, preorder: List[int]) -> bool:
# lower_bound = float('-inf')
# stack_top_idx = -1
#
# for p in preorder:
# if p < lower_bound:
# return False
#
# while stack_top_idx >= 0 and p > preorder[stack_top_idx]:
# lower_bound = preorder[stack_top_idx]
# stack_top_idx -= 1
#
# stack_top_idx += 1
# preorder[stack_top_idx] = p
#
# return True
Verify Preorder Sequence in Binary Search Tree in Java
class Solution {
public boolean verifyPreorder(int[] preorder) {
// lower_bound stores the value of the parent node whose right subtree
// we are currently traversing. Any subsequent node must be greater than this.
long lower_bound = Long.MIN_VALUE;
// Use the preorder array itself as a stack. stack_top_idx points to the top.
int stack_top_idx = -1;
for (int p : preorder) {
// If we find a node that is smaller than the lower_bound, it's a violation.
// This means a node in a right subtree is smaller than its grandparent-like ancestor.
if (p < lower_bound) {
return false;
}
// While the current node `p` is greater than the top of our virtual stack,
// it means we are moving to the right subtree. The popped nodes are
// roots of subtrees whose left branches are fully traversed.
while (stack_top_idx >= 0 && p > preorder[stack_top_idx]) {
// The popped node becomes the new lower bound.
lower_bound = preorder[stack_top_idx];
stack_top_idx--;
}
// Push the current node onto our virtual stack.
stack_top_idx++;
preorder[stack_top_idx] = p;
}
return true;
}
}
Verify Preorder Sequence in Binary Search Tree in C++
class Solution {
public:
bool verifyPreorder(vector<int>& preorder) {
// lower_bound stores the value of the parent node whose right subtree
// we are currently traversing. Any subsequent node must be greater than this.
long lower_bound = LONG_MIN;
// Use the preorder array itself as a stack. stack_top_idx points to the top.
int stack_top_idx = -1;
for (int p : preorder) {
// If we find a node that is smaller than the lower_bound, it's a violation.
// This means a node in a right subtree is smaller than its grandparent-like ancestor.
if (p < lower_bound) {
return false;
}
// While the current node `p` is greater than the top of our virtual stack,
// it means we are moving to the right subtree. The popped nodes are
// roots of subtrees whose left branches are fully traversed.
while (stack_top_idx >= 0 && p > preorder[stack_top_idx]) {
// The popped node becomes the new lower bound.
lower_bound = preorder[stack_top_idx];
stack_top_idx--;
}
// Push the current node onto our virtual stack.
stack_top_idx++;
preorder[stack_top_idx] = p;
}
return true;
}
};
Verify Preorder Sequence in Binary Search Tree in TypeScript
function verifyPreorder(preorder: number[]): boolean {
// lower_bound stores the value of the parent node whose right subtree
// we are currently traversing. Any subsequent node must be greater than this.
let lower_bound = -Infinity;
// Use the preorder array itself as a stack. stack_top_idx points to the top.
let stack_top_idx = -1;
for (const p of preorder) {
// If we find a node that is smaller than the lower_bound, it's a violation.
// This means a node in a right subtree is smaller than its grandparent-like ancestor.
if (p < lower_bound) {
return false;
}
// While the current node `p` is greater than the top of our virtual stack,
// it means we are moving to the right subtree. The popped nodes are
// roots of subtrees whose left branches are fully traversed.
while (stack_top_idx >= 0 && p > preorder[stack_top_idx]) {
// The popped node becomes the new lower bound.
lower_bound = preorder[stack_top_idx];
stack_top_idx--;
}
// Push the current node onto our virtual stack.
stack_top_idx++;
preorder[stack_top_idx] = p;
}
return true;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.