剑指 Offer 33. 二叉搜索树的后序遍历序列

题目链接:leetcode.

二叉搜索树后序遍历 [左子树 | 右子树 | 根节点]
且左子树都小于根节点,右子树都大于根节点
左右子树内部依然满足这样的条件

所以使用递归:

/*
执行用时:4 ms, 在所有 C++ 提交中击败了49.55%的用户
内存消耗:6.7 MB, 在所有 C++ 提交中击败了95.77%的用户 
*/

class Solution {
public:
	bool isPostorder(vector<int>& postorder, int start, int end)
	{
		if(end - start < 2)
			return true;
		int mid = start;
		while(postorder[mid] < postorder[end])
			mid++;
		for(int i = mid;i < end;++i)
		{
			if(postorder[i] < postorder[end])
				return false;
		}
		return isPostorder(postorder,start,mid-1) && isPostorder(postorder,mid,end-1);
	}
    bool verifyPostorder(vector<int>& postorder) {
        int N =  postorder.size();
        if(N < 3)
        	return true;
        return isPostorder(postorder, 0, N - 1); 
    }
};

大佬还说了个时间复杂度能降到O(n)的方法,单调栈,我没太看懂。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值