0255. Verify Preorder Sequence in Binary Search Tree
Last updated
Last updated
**Input:** preorder = [5,2,1,3,6]
**Output:** true**Input:** preorder = [5,2,6,1,3]
**Output:** falseclass Solution {
public boolean verifyPreorder(int[] preorder) {
// edge cases
if (preorder.length < 2) return true;
// walk
Stack<Integer> stack = new Stack<Integer>();
int parent = Integer.MIN_VALUE;
for (int i = 0; i < preorder.length; i++) {
if (preorder[i] <= parent) return false;
while (stack.size() > 0 && preorder[i] > stack.peek()) {
parent = stack.pop();
}
stack.push(preorder[i]);
}
// pass test, true
return true;
}
}class Solution {
public boolean verifyPreorder(int[] preorder) {
// edge cases
if (preorder.length < 2) return true;
// walk
int parent = Integer.MIN_VALUE;
for (int i = 0, j = 0; i < preorder.length; i++) {
if (preorder[i] <= parent) return false;
while (j > 0 && preorder[i] > preorder[j-1]) {
parent = preorder[--j];
}
preorder[j++] = preorder[i];
}
// pass test, true
return true;
}
}