剑指offer-二叉搜索树的后序遍历序列的判断

/*******************************************************************
Copyright(c) 2016, Tyrone Li
All rights reserved.
*******************************************************************/
// 作者:TyroneLi
//

/*
Q:
    二叉搜索树得后序遍历序列。
        输入一个整数数组序列,判断该序列是不是某二叉搜索树得后序遍历序列。
S:
    二叉搜索树得结构性质:左子树结点值 < 根节点值 < 右子树结点指。
    因此可以利用这个特性,递归判断左右子树和是不是满足这个特性。

*/

#include "../utils/BinaryTree.h"
#include <iostream>
#include <cstdio>
#include <cstdlib>

bool isPostOrderOfBST(int sequences[], int length)
{
    if(sequences == nullptr || length <= 0)
        return false;
    
    int root = sequences[length - 1];
    // 划分左子树得结构
    int i = 0;
    for(; i < length - 1; ++i)
    {
        if(sequences[i] > root)
            break;
    }
    // 划分右子树得结构
    int j = i;
    for(; j < length -1; ++j)
    {
        if(sequences[j] < root)
            return false;
    }

    bool leftChild = true;
    // 如果根节点存在左子节点
    if(i > 0)
        leftChild = isPostOrderOfBST(sequences, i);
    
    bool rightChild = true;
    if(j >= i && j < (length - 1))
        rightChild = isPostOrderOfBST(sequences + i, length-1);
    
    return leftChild && rightChild;

}

void test_1()
{
    std::cout << "test 1" << std::endl;

    int seq[] = {5,7,6,9,11,10,8};
    std::cout << isPostOrderOfBST(seq, 7) << std::endl;
}

void test_2()
{
    std::cout << "test 2" << std::endl;

    int seq[] = {7,4,6,5};
    std::cout << isPostOrderOfBST(seq, 4) << std::endl;
}

void test_3()
{
    std::cout << "test 3" << std::endl;

    // int seq[] = {5,7,6,9,11,10,8};
    int*seq = nullptr;
    std::cout << isPostOrderOfBST(seq, 7) << std::endl;
}

int main(int argc, char**argv)
{

    test_1();
    test_2();
    test_3();

    return 0;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值