Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cangoal/6e59f4bf256d594632fef8e9d6058bd8 to your computer and use it in GitHub Desktop.
Save cangoal/6e59f4bf256d594632fef8e9d6058bd8 to your computer and use it in GitHub Desktop.
LeetCode - 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?
// 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