Closed congr closed 6 years ago
O(N) time, constant space
class Solution {
public boolean verifyPreorder(int[] preorder) {
Stack<Integer> stack = new Stack();
int min = Integer.MIN_VALUE;
// pop order is inorder (sorted)
for(int p : preorder) {
if (min > p) return false;
while (!stack.isEmpty() && p > stack.peek())
min = stack.pop(); // !!! smaller value should pop first
stack.push(p);
}
return true;
}
}
https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/description/