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.
Consider the following binary search tree:
1 | 5 |
Example1:1
2Input: [5,2,6,1,3]
Output: false
Example2:1
2Input: [5,2,1,3,6]
Output: true
1 | class Solution { |
- stack: find global min, then bigger: later value1 vs before value backwards: stack.
while
: pop ALL stack values smaller than p; i.e.p
is the right child node now, pop all left/root nodes, until this “right node” becomes on the left children chain of ONE node. Then, “big-smallest-big” pattern again.- when
while
finishes, there is no node left or root top
, i.e.p
is global min again. - so
p
must be smallest. Any low larger thanp
would indicate this is not preorder. - If use an array, anchored at smallest value index, then compare values going towards 2 directions: not good, because if fact, that’s comparing just 2 children nodes, left and right. BUT, it is unknown which node is strictly the parent node of this right node. As a result, all nodes left/parent to this right node should be compared. In that case, a stack and while loop would be the best option.