LeetCode—剑指Offer:二叉搜索树的后序遍历序列(递归分治+辅助单调栈)

二叉搜索树的后序遍历序列(中等)

2020年9月1日

题目来源:力扣
在这里插入图片描述

解题
二叉搜索树的性质就是左子树比根节点小,右子树比根节点大。

二叉搜索树的后序遍历,有个规律就是最后一个点必为根节点。

按照后序遍历,可按是否小于根节点分成两个子树,如果分出来的是多个子树,则说明不符合二叉搜索树了。

参考自路飞大佬的题解

  • 递归分治
class Solution {
    
    
    public boolean verifyPostorder(int[] postorder) {
    
    
        return recur(postorder,0,postorder.length-1);
    }
    private boolean recur(int[] postorder,int l,int r){
    
    
        if(l>=r) return true;
        int tmp=l;
        //循环找出第一个比根节点大的数,以此拆分成左右两子树
        while(postorder[tmp]<postorder[r]){
    
    
            tmp++;
        }
        int center=tmp;
        //继续给tmp累加值
        while(postorder[tmp]>postorder[r]){
    
    
            tmp++;
        } 
        //首先判断tmp能否走到末尾,不能走到末尾则说明出现多个子树,为false
        return tmp==r && recur(postorder,l,center-1) && recur(postorder,center,r-1);
    }
}

在这里插入图片描述

  • 辅助单调栈
class Solution {
    
    
    public boolean verifyPostorder(int[] postorder) {
    
    
        //定义栈来存放递增的数值
        Stack<Integer> stack=new Stack<>();
        //定义一个正无穷大的数值来初始化根节点
        int root=Integer.MAX_VALUE;
        for(int i=postorder.length-1;i>=0;i--){
    
    
            int tmp=postorder[i];
            //当递减时,数值必须满足小于根节点这个规律,否则不是二叉搜索树
            if(tmp>root) return false;
            //当不为空的时候,且栈顶元素比当前数值大,说明开始递减
            while(!stack.isEmpty()&&stack.peek()>tmp){
    
    
                //更新root到仅比当前数值大
                root=stack.pop();
            }
            stack.add(tmp);
        }
        return true;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/108333269