Topic:
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?
Links: http://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/
Exercises
Use stack to simulate preorder traversal, mid, left, right. The main code is a reference to Stefan Pochmann's solution.
Time Complexity-o (n), Space Complexity-o (LOGN)
Public classSolution { Public BooleanVerifypreorder (int[] preorder) { intLow =Integer.min_value; Stack<Integer> stack =NewStack<>(); for(intI:preorder) { if(I <Low )return false; while(!stack.isempty () && i >Stack.peek ()) Low=Stack.pop (); Stack.push (i); } return true; }}
No solution using Stack,space complexity O (1), using the original array
Public classSolution { Public BooleanVerifypreorder (int[] preorder) { intLow = integer.min_value, index =-1; for(intI:preorder) { if(I <Low )return false; while(Index >= 0 && i >Preorder[index]) Low= preorder[index--]; preorder[++index] =i; } return true; }}
Reference:
Https://leetcode.com/discuss/51543/java-o-n-and-o-1-extra-space
Https://leetcode.com/discuss/52060/72ms-c-solution-using-one-stack-o-n-time-and-space
Https://leetcode.com/discuss/65241/ac-python-o-n-time-o-1-extra-space
Https://leetcode.com/discuss/68862/my-c-solution-easy-to-understand
255. Verify Preorder Sequence in Binary Search Tree