Sword Finger - Postorder Traversal Sequence of Binary Search Trees

Input an integer array to determine whether the array is the result of a post-order traversal of a binary search tree. Returns true if so, false otherwise. Assume that any two numbers in the input array are different from each other

Idea: In the sequence obtained by post-order traversal, the last number is the value of the root node of the tree. The previous numbers in the array can be divided into two parts. The first part is the value of the left subtree node, which are all smaller than the value of the root node. The second part is the value of the right subtree node, both of which are larger than the root node

#include <stdio.h>
#include <iostream>
using namespace std;

//Determine whether this array is the result of a post-order traversal of a binary tree search tree
bool VerifySquenceOfBST(int sequence[],int length) //parameter 1 is the array parameter 2 is the size of the array
{
    if(sequence==NULL || length<=0)
        return false;
    int root=sequence[length-1]; //According to the nature of the post-order traversal of the binary search tree, the last number of the array is the root of the tree
    //First find the dividing point of the left and right subtrees in the array because the left subtree of the root in the search tree is smaller than the root, and the right subtree is larger than the root
    int i=0;
    for(;i<length-1;++i)
    {
        if(sequence[i]>root)
            break; //The i value of the position where the break occurs is the position where the first right child node appears
    }

    int j=i;
    for(;j<length-1;++j) //Determine whether the nodes in the right subtree corresponding to the array are all larger than the root node
    {
        if(sequence[j]<root)
            return false;
    }

    / / Determine whether the left subtree is a binary search tree
    bool left=true;
    if(i>0)
        left=VerifySquenceOfBST(sequence,i);

    / / Determine whether the right subtree is a binary search tree
    bool right=true;
    if(i<length-1)
        right=VerifySquenceOfBST(sequence+i,length-i-1);

    return (left && right);
}

intmain()
{
    int array[]={5,7,6,9,11,10,8};

    if(VerifySquenceOfBST(array,sizeof(array)/sizeof(array[0])))
        cout<<"It is an Binary search tree"<<endl;
    else
        cout<<"It is not an Binary search tree"<<endl;

    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324473884&siteId=291194637