zoukankan      html  css  js  c++  java
  • 二叉搜索树的后序遍历序列

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

    解法是递归判断,先找根节点,划分左右子树递归求解。边界需要特殊考虑。

    AC代码:

    public class Solution {
        public boolean VerifySquenceOfBST(int[] sequence) {
            if(sequence == null || sequence.length <= 0)
                return false;
            
            int len  = sequence.length;
            
            return solve(sequence, 0, len-1);
            
        }
        
        public boolean solve(int[] sequence, int start, int end) {
            if(start == end)
                return true;
            int root = sequence[end];
            //System.out.println(root);
            int index = start;
            for(; index < end; index ++) {
                if(sequence[index] > root)
                    break;
            }
            
            for(int j=index; j<end; j++) {
                if(sequence[j] < root)
                    return false;
            }
            
            boolean left = true;
            if(index > start)
                left = solve(sequence, start, index-1);
            
            boolean right = true;
            if(index < end)
                right = solve(sequence, index, end-1);
            
            return  (left && right) ;
            
        }
    }
  • 相关阅读:
    linux -- 部署java服务器(3) linux安装redis
    linux 安装php8
    linux mysql查看日志
    linux mysql常用的命令
    perl heredoc
    perl数值进制
    提问的智慧
    How to ask question the smart way
    PERL命令行
    图灵/异步图书
  • 原文地址:https://www.cnblogs.com/wxisme/p/5406498.html
Copyright © 2011-2022 走看看