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

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

    思路

    分治法。
    不断地确定出左子树区间和右子树区间,并且判断:左子树区间的所有结点值 < 根结点值 < 右子树区间所有结点值。
    序列最后一个数是根节点,序列第一个大于根节点的数是潜在的右子树第一个结点。
    时间复杂度O(n²),空间复杂度O(n)。

    代码1

    public class Solution {
        private boolean helper(int[] sequence, int start, int root) {
            if(start >= root)    return true;
            // 代码1为两段局部循环,mid的初始值容易出错,代码2的全局循环不存在这个问题
            int mid = root-1;
            for(int i = start; i < root; i++) {
                if(sequence[i] > sequence[root]) {
                    mid = i;
                    break;
                }
            }
            for(int j = mid+1; j < root; j++) {
                if(sequence[j] < sequence[root]) {
                    return false;
                }
            }
            return helper(sequence, start, mid-1) && helper(sequence, mid, root-1);
        }
        
        public boolean VerifySquenceOfBST(int [] sequence) {
            if(sequence == null || sequence.length == 0)    return false;
            return helper(sequence, 0, sequence.length - 1);
        }
    }
    

    代码2

        private boolean helper(int[] sequence, int start, int root) {
            if(start >= root)    return true;
            int mid;
            for(mid = start; mid < root; mid++) {
                if(sequence[mid] > sequence[root]) {
                    break;
                }
            }
            for(int j = mid+1; j < root; j++) {
                if(sequence[j] < sequence[root]) {
                    return false;
                }
            }
            return helper(sequence, start, mid-1) && helper(sequence, mid, root-1);
        }
    
  • 相关阅读:
    .net下的span和memory
    linux下mysql自动备份脚本
    mysqldump参数详细说明(转)
    Apache参数的优化(转)
    shell中set的用法(转)
    [转贴] start-stop-daemon命令
    Linux命令service
    分享三个好用的装饰器(转)
    python语法32[装饰器decorator](转)
    mongodb exception in initAndListen: 12596 old lock file, terminating解决方法
  • 原文地址:https://www.cnblogs.com/ustca/p/12335233.html
Copyright © 2011-2022 走看看