使用二叉树的相关定义及函数在:二叉树最小结构(C++版本)
注意点:
假设左子树小于等于根节点,右子树大于根节点。
实现代码:
bool IsPostOrder(int* pData, int begin, int end)
{
if (nullptr == pData) return false;
if (begin > end) return false;
if (begin == end) return true;// 只有一个节点
// 找出左右子树的分解点,如果左右子树都有,
// 区间分别为[begin, lassLessIdx - 1], [lassLessIdx, end - 1]
// pData[end]根节点
int lastLessIdx = 0;
for (lastLessIdx = begin; lastLessIdx < end; ++lastLessIdx )
{
if (pData[idx] > pData[end]) break;
}
// 判断右子树是否都大于根节点
for (int idx = lastLessIdx; idx < end; ++idx)
{
if (pData[idx] <= pData[end]) return false;
}
bool leftTreeResult = true;
bool rightTreeResult = true;
// 如果有右子树 (lastLessIdx == end无右子树) 如果有左子树 (0 == lastLessIdx无左子树)
if (lastLessIdx > begin) leftTreeResult = IsPostOrder(pData, begin, lastLessIdx - 1);
if (lastLessIdx < end) rightTreeResult = IsPostOrder(pData, lastLessIdx, end - 1);
return leftTreeResult && rightTreeResult;
}