The original title link is here: https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/
Topic:
Given An array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
Assume each of the sequence is unique.
Follow up:
Could does it using only constant space complexity?
Exercises
Method 1 simulates the preorder with a stack. The left subtree is placed in the stack. The encounter is larger than the stack top, indicating that a right subtree with top root is encountered, and the Zuozi together with root pops out.
Low is the current lower bound, pop out to show that the left sweep is finished, it is impossible to appear smaller, so the update. It is not preorder to encounter a small lower than low.
Time Complexity:o (n). Space:o (LOGN).
Method 2 is the ability to implement the stack on the array itself.
Time Complexity:o (n). Space:o (1).
AC Java:
1 Public classSolution {2 Public BooleanVerifypreorder (int[] preorder) {3 /*4 //method 15 int low = Integer.min_value;6 stack<integer> Stk = new stack<integer> ();7 for (int num:preorder) {8 if (num < low) {9 return false;Ten } One While (!stk.isempty () && stk.peek () < num) { A Low = Stk.pop (); - } - Stk.push (num); the } - return true; - */ - intindex =-1; + intLow =Integer.min_value; - for(intNum:preorder) { + if(Num <Low ) { A return false; at } - while(Index >= 0 && Preorder[index] <num) { -Low = preorder[index--]; - } -Preorder[++index] =num; - } in return true; - } to}
Leetcode Verify Preorder Sequence in Binary Search Tree