255. Verify Preorder Sequence in Binary Search Tree π
Description
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 <= 1041 <= preorder[i] <= 104- All the elements of
preorderare unique.
Follow up: Could you do it using only constant space complexity?
Solutions
Solution 1
Thinking
Rebuilding the BST is heavier than needed. Preorder visits root, left, then right; a decreasing stack holds nodes that have not yet turned to their right subtree.
A value below the last popped lower bound is invalid. Otherwise pop every smaller top as the new bound and push the current value.
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
