Verify that a list is not a BST preorder traversal sequence.
Given An array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
Assume each of the sequence is unique.
Follow up:
Could does it using only constant space complexity?
Observe this example: [8, 3, 1, 6, 4, 7, 10, 14, 13],
8, 3, 1 These three consecutive descending numbers indicate that we have been walking to the left until we get to 6 from root.
6 is supposed to be 3 right child, because he is bigger than 3, but less than 8. At this point the indicator should be equal to 3. This means that all the numbers in the list cannot be less than 3. Since 6 is the right child of 3, it shows that 3 itself and his left subtree have been traversed, and all the numbers after that should be greater than 3.
Then it drops again until 7 appears. You should update min to 6. Then all the numbers should be greater than 6. And so on All we have to do is maintain a stack. If Elem < min, return False. If Elem < stack[-1], push the elem into the stack. If Elem > Stack[-1], then pop out of the stack for those numbers smaller than elem, and update min. Specific steps to look at:
Min =-maxint
8,
8, 3,
8, 3, 1
8, 6 min = 3
8, 6, 4,
8, 7 min = 6
Ten, Min = 8
, min = 10
14, 13
1 classsolution (object):2 defVerifypreorder (self, preorder):3 """4 : Type Preorder:list[int]5 : Rtype:bool6 """7stack = []8Min = -0x7fffffff9 forEleminchPreorder:Ten ifElem <min: One returnFalse A whileStack andSTACK[-1] <Elem: -Min =Stack.pop () - stack.append (elem) the returnTrue
Follow up: How do I verify Postorder and Midorder?
A: The middle sequence is an ascending sequence.
The order of Postorder is left-right-root, then this example should be [1, 4, 7, 6, 3, 13, 14, 10, 8]
The easy way to do this is to start with the root verification, because after the next root, we can first reverse the list. Then the idea is similar to the above, except to decrease to increment. Record min changes to record Max.
Leetcode 255. Verify preorder Sequence in Binary Search Tree