24. 二叉搜索树的后续遍历序列(c++版本)

使用二叉树的相关定义及函数在:二叉树最小结构(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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值