LCOF剑指offer--面试题33. 二叉搜索树的后序遍历序列

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。

参考以下这颗二叉搜索树:

     5
    / \
   2   6
  / \
 1   3

示例 1:

输入: [1,6,3,2,5]
输出: false

示例 2:

输入: [1,3,2,6,5]
输出: true

提示:

数组长度 <= 1000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分析:
递归
解答:

class Solution {
public:
    bool verifyPostorder(vector<int>& postorder) {
        if(postorder.size()<2) return true;

        return helper(postorder,0 , postorder.size()-1);
    }

    bool helper(vector<int>& postorder,int begin, int end){
        if(begin>=end) return true;//考虑了左右子树为空的时候

        int i = begin;
        while(postorder[i]<postorder[end]){
            i++;
        }

        int boundary = i;

        for(;i<end;i++){
            if(postorder[i]<postorder[end]) return false;
        }

        return helper(postorder, begin, boundary-1)&&helper(postorder,boundary,end-1);


    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!我是 ChitGPT AI,很高兴能够为您解答问题。 针对您提出的问题,我可以给出以下解答: 对于输入的正整数 target,可以通过双针法求出所有和为 target 的连续正整数序列。具体地,我们设两个针 small 和 big 分别表示连续正整数序列的起点和终点,初始时两个针都向 1,即序列为 {1}。然后如果序列的和小于 target,我们将 big 针右移一位,扩展序列的长度;如果序列的和大于 target,我们将 small 针右移一位,缩小序列的长度;如果序列的和等于 target,即找到了一个符合要求的连续正整数序列,将其加入结果列表中,并将 big 针右移一位,继续寻找下一个连续序列。 具体实现过程中,我们需要注意以下几点: 1. 如果区间和小于 target,应该扩展序列的末尾,即将 big 针右移一位; 2. 如果区间和大于 target,应该缩小序列的开头,即将 small 针右移一位; 3. 如果 big 针移动到了 target 的一半位置,就没有必要再继续往下寻找了,因为后面的数肯定不符合要求。 下面是完整代码实现,您可以参考: ```python def findContinuousSequence(target: int) -> List[List[int]]: res = [] small, big = 1, 2 while big <= target // 2 + 1: s = sum(range(small, big + 1)) if s == target: res.append(list(range(small, big + 1))) big += 1 elif s < target: big += 1 else: small += 1 return res ``` 希望我的回答能对您有所帮助,如果您还有其他问题,欢迎随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值