剑指offer-33 二叉搜索树的后序遍历序列

这篇博客讨论了一种验证给定数组是否为二叉搜索树后序遍历结果的方法。通过递归地检查后序遍历的特性,即左子树+右子树+根节点,并确保左子树的所有值小于根节点,右子树的所有值大于根节点,可以判断数组是否符合要求。提供的代码实现了一个名为`Solution`的类,包含`verifyPostorder`和`test`两个方法,用于完成此验证过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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

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

     5
    / \
   2   6
  / \
 1   3

示例 1:

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

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

提示:

数组长度 <= 1000

1、前提是 二叉搜索树

2、二叉搜索树的后序遍历序列满足条件是

        1)左子树+右子树+根

        2)左子树序列中的值必须都小于根,右子树序列中的值必须都大于根

        3)左子树序列必须满足后序遍历序列条件,右子树序列必须满足后序遍历序列条件

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        if(postorder==null||postorder.length==0)
            return true;
        return test(postorder,0,postorder.length-1);

    }
    public boolean test(int[] postorder,int start,int end)
    {
        if(start>=end)
            return true;
        int temp=postorder[end];
        int index=start;
        while(index<=end&&postorder[index]<temp)
            index++;    //找到左子树序列为[start,index-1],右子树序列为[index,end]
        int t=index;
        while(t<=end&&postorder[t]>temp)
            t++;
        return (t==end)&&test(postorder,start,index-1)&&test(postorder,index,end-1);//end要减一
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值