Created
April 21, 2016 04:44
-
-
Save cangoal/6e59f4bf256d594632fef8e9d6058bd8 to your computer and use it in GitHub Desktop.
LeetCode - Verify Preorder Sequence in Binary Search Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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? | |
// use stack | |
public boolean verifyPreorder(int[] preorder) { | |
Stack<Integer> stack = new Stack<Integer>(); | |
int low = Integer.MIN_VALUE; | |
for(int i = 0; i < preorder.length; i++){ | |
if(preorder[i] < low) return false; | |
while(!stack.isEmpty() &&stack.peek() < preorder[i]){ | |
low = stack.pop(); | |
} | |
stack.push(preorder[i]); | |
} | |
return true; | |
} | |
// O(1) space complexity | |
public boolean verifyPreorder(int[] preorder) { | |
int low = Integer.MIN_VALUE, i = -1; | |
for (int p : preorder) { | |
if (p < low) | |
return false; | |
while (i >= 0 && p > preorder[i]) | |
low = preorder[i--]; | |
preorder[++i] = p; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment