255. Verify Preorder Sequence in Binary Search Tree

Source: Internet
Author: User

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?

Links: http://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/

Exercises

Use stack to simulate preorder traversal, mid, left, right. The main code is a reference to Stefan Pochmann's solution.

Time Complexity-o (n), Space Complexity-o (LOGN)

 Public classSolution { Public BooleanVerifypreorder (int[] preorder) {        intLow =Integer.min_value; Stack<Integer> stack =NewStack<>();  for(intI:preorder) {            if(I <Low )return false;  while(!stack.isempty () && i >Stack.peek ()) Low=Stack.pop ();        Stack.push (i); }                return true; }}

No solution using Stack,space complexity O (1), using the original array

 Public classSolution { Public BooleanVerifypreorder (int[] preorder) {        intLow = integer.min_value, index =-1;  for(intI:preorder) {            if(I <Low )return false;  while(Index >= 0 && i >Preorder[index]) Low= preorder[index--]; preorder[++index] =i; }                return true; }}

Reference:

Https://leetcode.com/discuss/51543/java-o-n-and-o-1-extra-space

Https://leetcode.com/discuss/52060/72ms-c-solution-using-one-stack-o-n-time-and-space

Https://leetcode.com/discuss/65241/ac-python-o-n-time-o-1-extra-space

Https://leetcode.com/discuss/68862/my-c-solution-easy-to-understand

255. 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.