forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path_255.java
More file actions
30 lines (24 loc) · 735 Bytes
/
_255.java
File metadata and controls
30 lines (24 loc) · 735 Bytes
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;
/**
* 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> path = new Stack();
for (int p : preorder) {
if (p < low) {
return false;
}
while (!path.empty() && p > path.peek()) {
low = path.pop();
}
path.push(p);
}
return true;
}
}