255. Verify Preorder Sequence in Binary Search Tree
use recursion
preorder, so root left right, right must be larger than root, or it's false
T: O(nlogn), logn is the tree height
S: O(nlogn)
classSolution {publicbooleanverifyPreorder(int[] preorder) {returndfs(preorder,0,preorder.length-1); }privatebooleandfs(int[] preorder,int start,int end) {if (start > end) {returntrue; }int root = preorder[start];int i = start +1;while (i <= end && preorder[i] < root) { i++; }for (int right = i; right <= end; right++) {if (root > preorder[right]) {returnfalse; } }returndfs(preorder, start +1, i-1)&&dfs(preorder, i, end); }}/*use recursion T: O(nlogn)S: O(nlogn)*/
2. use mono stack
T: O(n)
S: O(n)
classSolution {publicbooleanverifyPreorder(int[] preorder) {Deque<Integer> stack =newArrayDeque<>();int maxA =Integer.MIN_VALUE;for (int pre : preorder) {if (pre < maxA) {returnfalse; }while (!stack.isEmpty() && pre >stack.peek()) { maxA =Math.max(maxA,stack.peek());stack.pop(); }stack.push(pre); }returntrue; }}/*amax_a [......b.......][......c......]if this is a preoder, when we find a < b, update max_a, we need max_a < c for every c after bmax_a < b && max_a < c => true, or is falseuse mono stack to find max_a, so maintain a descreasing mono stack, when we meet larger one, means we got a < bso pop a, update max(a, max_a)...others just push a into stackand in the following step, if we can find a new number is smaller than max_a, return falseT: O(n)S: O(n)*/