Problem
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
You may assume each number in the sequence is unique.
Follow up
Could you do it using only constant space complexity?
Examples
Consider the following binary search tree:
|
|
Example1
|
|
Example2
|
|
Example3
|
|
Example4
|
|
Solution
Method 1 - Using Monotonic Decreasing Stack and Keeping Lower Bound
Key Observations
- In a BST, for any node, all elements in its left subtree are smaller, and all elements in its right subtree are larger.
- In preorder traversal, we first visit the root, then recursively visit the left and right subtrees.
Validation
- While processing elements in the array, maintain the boundary (referred to as the
low
value) below which values cannot appear (since they belong to the left subtree). - Use a stack to simulate the traversal and validate the sequence:
- Push nodes onto the stack until nodes in the right subtree appear.
- Update the boundary (
low
) when backtracking occurs.
Algorithm
- Walk through the preorder traversal,
left subtree value < root's value < right subtree's value
- We can see that,
root value< upcoming right value in the array
- If we know the root value, we can use it to determine whether if upcoming value is valid. So we use a
lower
to denote the lower_bound, which is also the root value, of the tree. - Use a stack to store the array from
root
toleft subtree
, whenever reach a node has greater value, pop value out of stack. Then store the last pop out value as lower bound.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the size of the input array, as each element in the array is processed once. - 🧺 Space complexity:
O(n)
because the stack can contain up ton
elements in the worst case. However, for well-balanced trees, the stack size is limited to the depth of the tree (O(log n)
).
Dry Run
|
|
Lets look at algo:
|
|