Leetcode Verify Preorder Sequence in Binary Search Tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.