/*******************************************************************
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;
}
剑指offer-二叉搜索树的后序遍历序列的判断
最新推荐文章于 2023-03-19 11:29:26 发布