您的位置:首页 > 其它

【100题】判断一个序列是不是一个BST的后序遍历

2012-07-18 17:57 447 查看
//验证一个序列,是不是某个二叉查找树的后续遍历
#include <iostream>
using namespace std;

bool IsBST(int squence[], int length)
{
	if(squence == NULL || length <= 0)
	{
		return false;
	}
	//最后一个值是根节点
	int root = squence[length - 1];
	//前一半是root的左子树,应该都小于root
	int i=0;
	for(;i < length-1; ++i)
	{
		if(squence[i] > root)
		{
			//一旦遇到大的,直接跳出循环,进入到右子树去
			break;
		}
	}
	//后半部分是root的右子树,应该都大于root
	int j = i;
	for(;j<length-1;++j)
	{
		if(squence[j] < root)
		{
			//一旦遇到小的,直接返回,说明不是BST
			return false;
		}
	}
	
	//左边的信号量,先置为true
	bool left = true;
	if(i > 0)
	{
		//递归调用左边的,看看是不是BST
		left = IsBST(squence,i);
	}

	//右边的信号量,先置为true
	bool right = true;
	if(i <  length-1)
	{
		//递归调用右边的,看看是不是BST
		right = IsBST(squence+i,length-i-1);
	}
	//两边都是BST,则就是BST!!
	return (left&&right);
}

void main()
{
	int BST[] = {1,7,5,12,18,15,10};
	IsBST(BST,sizeof(BST)/sizeof(BST[0])) ? cout << "BST"<<endl : cout << "not BST"<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐