24. Post-order traversal sequence of binary search tree

  Question: 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. Suppose any two numbers of the input array are different from each other.

  Idea: Because it is a binary search tree, the left subtree of each root node is smaller than the root node, and the right subtree is larger than the root node.
  For example, if you enter {5, 7, 6, 9, 11, 10, 8}, the post-order traversal must be the last traversal of the root node, so 8 is the root node, and then because 5, 7, 6 are smaller than 8, so in 8 is on the left, 9, 11, and 10 are on the right. And so on for this array.
  For example, input {7, 4, 6, 5}, 5 is the root node, because 7 is greater than 5, so there is no left subtree, but 4 is less than 5, which is contradictory, so it does not match.

#include<iostream>
#include<cstdio>
#include<deque>
using namespace std;

bool VerifyBst(int sequence[], int length)
{
    if (sequence == NULL || length <= 0)
    {
        return false;
    }

    int root = sequence[length-1];

    //在二叉搜索树中左子树结点小于根结点
    int i = 0;
    for (; i < length - 1; i++)
    {
        if (sequence[i] > root)
        {
            break;
        }

    }

    //右子树大于根结点
    int j = i;
    for (; j < length - 1; j++)
    {
        if (sequence[j] < root)
        {
            return false;
        }
    }

    //判断左子树是不是二叉搜索树
    bool left = true;
    if (i > 0)
    {
        left = VerifyBst(sequence, i);
    }

    //判断右子树是不是二叉搜索树
    bool right = true;
    if (i < length - 1)
    {
        right = VerifyBst(sequence + i, length - i - 1);
    }

    return (left && right);
}

int main()
{
    int num[7] = {10,7,6,9,11,10,8};
    bool result = VerifyBst(num, 7);
    if (result == 1)
    {
        cout << "true" << endl;
    }
    else
    {
        cout << "false" << endl;
    }
    //cout << (result == 1)?true : false << endl;

    return 0;
}

 

Related topic:
  Input an array of integers and determine whether the array is the result of a preorder traversal of a binary search tree. This is similar to the post-order traversal of the previous problem, except that in the sequence obtained by the pre-order traversal, the first number is the value of the root node.

  By analogy:
  If the interview question is to deal with the traversal sequence of a binary tree, we can first find the root node of the binary tree, and then split the traversal sequence of the entire tree into the subsequence corresponding to the left subtree and the right subsequence based on the root node. The subsequences corresponding to the tree are then processed recursively.

Guess you like

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