Monday, April 18, 2016

LeetCode Q255: Verify Preorder Sequence in Binary Search Tree

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?

Solution:
Use a stack to simulate the pre-order traversal. 
Also, should refer to following solutons:
1. https://leetcode.com/discuss/52060/72ms-c-solution-using-one-stack-o-n-time-and-space
2. https://leetcode.com/discuss/52744/c-o-n-log-n-recursive-solution
3. https://leetcode.com/discuss/89904/52ms-c-o-1-space-o-n-time-commented-code

Round 2 solutoin:
Tracking the upper bound and lower bound of left and right branches. To get the separate position of the branches, use binary search.

No comments:

Post a Comment