二叉搜索树的后序

https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&tqId=11176&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

 

思路:

比如给定序列 4 8 6 12 16 14 10

10是根节点,判断10左子树(4 8 6 )和右子树(12 16 14 )是否满足比10小,比10大,如果满足

继续判断(4 8 6 )和 (12 16 14 )各自是否满足,可以看出明显就是递归


class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) 
	{
		int length = sequence.size();
		if(length == 0)
			return false;
		if( check(sequence , 0, length - 1) )
			return true;
		else
			return false;

	}
	//检查序列a到b有没有满足二叉搜索树
	bool check(vector<int> sequence, int a, int b)
	{
		
		if(a >= 0 && a < b)//不止一个元素的时候
		{
			int root = sequence[b];
			int start = -1;
			for(int i = a; i < b; i++)
			{
				if(sequence[i] < root)
					start = i;
				else
					break;
			}
			if(start == -1)//二叉搜索树根节点没有左子树
			{
				for(int i = a;i < b; i++)
				{
					if(sequence[i] < root)//右子树比根节点小
						return false;
				}
				return check(sequence, a, b-1);//递归检查右子树是否满足二叉搜索树

			}
			else//二叉搜索树有左子树
			{
				for(int i = start + 1; i < b; i++)//检查右子树是否满足
				{
					if(sequence[i] < root)
						return false;//不满足
				}
				//检查根节点的左子树和右子树
				return check(sequence, a, start) && 
					check(sequence, start + 1, b-1);
			}


		}

		return true;//序列只有一个元素的时候当做二叉搜索树了


	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值