每日算法三道之判定一个给定序列能否为二叉搜索树的后序遍历结果

核心思想:分冶、递归
思路:由于是一颗二叉搜索树,中序遍历为从小到大的结果,相当于已给定,其实转换为是否能根据中序和后序唯一确定一个二叉树。
根据后序遍历找到根,再找到中序遍历中此根节点的位置,从而可以将后序遍历分为左右两部分,判断左半边部分是否都小于根节点同时右节点都大于根节点,若是,则将左右两部分依次递归此过程,否则不是一个二叉搜索树的后序遍历结果。
代码:

/**************************************************
功能:判断一个给定的二叉搜索树的后序遍历是否正确
@athor: rly
@date:  2018-3-7
**************************************************/


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool isPostSeachTrue(int *post, int *in,int size)
{
    if (size <= 0)
    {
        return true;
    }
    int root = post[size - 1];
    int rootIndex;
    for (rootIndex = 0; rootIndex < size; rootIndex++)
    {
        if (in[rootIndex] == root)
        {
            break;
        }
    }                                   //找到根节点在中序遍历中的位置
    int leftNum = rootIndex;
    int rightNum = size - (leftNum + 1);

    int i, j;
    for (i = 0, j = leftNum + 1; i < leftNum,j < rightNum; i++, j++)
    {
        if (post[i] >= root || post[j] <= root)
        {
            return false;
        }                                //若左边比根大或者右边比根小,则不是后序遍历结果
    }

    isPostSeachTrue(post, in, leftNum);
    isPostSeachTrue(post + leftNum, in + leftNum + 1, rightNum);
    return true;
}

猜你喜欢

转载自blog.csdn.net/rlyhaha/article/details/79476542