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.