二叉搜索树的后序遍历序列

二叉搜索树的后序遍历序列

https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&&tqId=11176&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

二叉树的后续遍历:先访问左节点,再访问右节点,最后访问根节点
所以一个后续遍历的数组,最后一位肯定是二叉树的根节点

何为二叉搜索树:左节点必定小于根节点,右节点必定小于根节点;左子树和右子树也是二叉搜索树

所以思路就来了:
我们可以直接拿到二叉树的根节点,然后找到其左子树的所有节点和右子树的所有节点,
然后切成两个二叉树,继续递归调用去做同样的判断

public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence == null || sequence.length == 0)
            return false;
        return toCut(sequence,0,sequence.length-1);
    }

    public boolean toCut(int[] arr,int first,int last){
        if(last-first <= 1){
            return true;
        }
        int rootVal = arr[last];
        int cutIndex = first;
        while(cutIndex < last && arr[cutIndex] <= rootVal)
            cutIndex++;
        for(int i = cutIndex; i < last; i++){
            if(arr[i] < rootVal)
                return false;
        }
        return toCut(arr,first,cutIndex-1) && toCut(arr,cutIndex,last-1);
    }
剑指offer 文章被收录于专栏

为刷过的每一道题都书写一篇题解,便于重复练习~

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-18 18:30
点赞 评论 收藏
分享
07-14 13:47
门头沟学院 Java
Lynn012:你评估好自己的位置了吗《顶尖应届》
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务