forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_255.java
30 lines (25 loc) · 796 Bytes
/
_255.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.fishercoder.solutions;
import java.util.Stack;
/**
* 255. 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?
*/
public class _255 {
public boolean verifyPreorder(int[] preorder) {
int low = Integer.MIN_VALUE;
Stack<Integer> stack = new Stack();
for (int p : preorder) {
if (p < low) {
return false;
}
while (!stack.empty() && p > stack.peek()) {
low = stack.pop();
}
stack.push(p);
}
return true;
}
}