面试题---判断整数序列是不是二元查找树的后序遍历结果

判断整数序列是不是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
    8
   / /
  6  10
/ / / /
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
代码如下:
#include<iostream>
using namespace std;

bool VerifySequence(int *sequence,int length)
{
	bool left = true;
	bool right = true;
	int i,j;
	int root = sequence[length - 1];
	for(i = 0; i < length - 1; i++)
	{
		if(sequence[i] > root)
			break;
	}

	for(j = i; j < length - 1; j++)
	{
		if(sequence[j] < root)
			return false;
	}

	if(i > 0)
		left = VerifySequence(sequence,i);
	if(i < length - 1)
		right = VerifySequence(sequence + i,length - 1 - i);
	
	return (left&&right);
}


int main()
{
	int sequence[] = {5,7,6,9,11,10,8};
	VerifySequence(sequence,7) ? cout<<"这个序列是二叉查找树的后序遍历!"<<endl : cout<<"这个序列不是二叉查找树的后序遍历!"<<endl ;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值