Determine whether a post-order traversal is correct

Source: Internet
Author: User

Question:

A binary search tree returns a post-order traversal to determine whether the post-order traversal is correct.

Analysis:

Method 1, according to the middle and back order

A binary tree can be obtained by using the forward and backward orders. The central order of a binary search tree is obviously the normal sorting of all numbers. Therefore, we first sort all the numbers in the back order. The time complexity is O (nlogn ), then, based on the Post-order and Middle-order traversal, determine whether a binary tree can be created.

The total time complexity is O (nlogn ).

Method 2: directly use the nature of the Binary Tree

Obviously, the last number of the Post-sequential traversal is the root node. Then, based on the nature of the binary tree, we divide the preceding number into two parts. The first part is the number smaller than the root node, the numbers that follow are all numbers greater than the root node. Then, the recursive method is used to determine whether the binary tree is correctly searched for post-sequential traversal.

The Code is as follows:

# Include <iostream> # include <cstdlib> # include <cstdio> using namespace STD; bool verifybst (int * a, int Len) {if (a = NULL | Len <0) return false; If (LEN = 0) // If the length is 0, return true; int I = 0; while (I <len-1) // find the first number greater than the root node {if (a [I]> A [Len-1]) break; I ++ ;} int J = I; while (j <len-1) // determine whether the numbers on the right are greater than the root node {if (a [J] <A [Len-1]) return false; j ++;} return verifybst (A, I) & verifybst (a + I, len-I-1); // recursive call, determine whether the number on the left and right meets the condition} int main () {int A [] = {,}; cout <verifybst (A, sizeof () /sizeof (A [0]) <Endl; return 0 ;}

Summary:

During interviews, questions about binary trees often occur. You must learn to mine the features of Binary Trees and use them to solve problems.

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.