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

    题目描述

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

     思路:
    在后序遍历得到的序列中,最后一个元素是根节点。数组中前面的元素可以分分2部分,左部分是比根节点小的,是左子树,
    右部分是比根节点大的, 是右子树。

    public class Solution {
        public boolean VerifySquenceOfBST(int [] sequence) {
            if(sequence.length==0) return false;
            if(sequence.length==1) return true;
            return ju(sequence, 0, sequence.length-1);
        }
        public boolean ju (int [] a,int start,int root){
            if(start>root) return true;
            int i = root;
            while(i>start &&a[i-1]>a[root]){
                i--;
            }
            for(int j= start;j < i-1;j++){
                if(a[j]>a[root])
                    return false;
            }
            return ju(a,start,i-1)&& ju(a,i,root-1);
            }
    }
     1 public class Solution {
     2     public boolean VerifySquenceOfBST(int [] sequence) {
     3         if(sequence.length==0) return false;
     4         if(sequence.length==1) return true;
     5         return judge(sequence, 0, sequence.length-1);
     6     }
     7     public boolean judge(int [] a,int start,int end){
     8         if(start>end) return true;//全都遍历完了,说明没有剩下的元素,说明符合条件
     9         int root = a[end];
    10         int mid = start;
    11         //找到右部分的头
    12         while(a[mid]<root)
    13             mid++;
    14         //判断右部分是否有不满足条件的
    15         for(int j= mid;j <end-1;j++)
    16             if(a[j]<root)   return false;
    17         return judge(a,start,mid-1)&& judge(a,mid,end-1);
    18         }
    19 }
  • 相关阅读:
    hdu5728 PowMod
    CF1156E Special Segments of Permutation
    CF1182E Product Oriented Recurrence
    CF1082E Increasing Frequency
    CF623B Array GCD
    CF1168B Good Triple
    CF1175E Minimal Segment Cover
    php 正则
    windows 下安装composer
    windows apache "The requested operation has failed" 启动失败
  • 原文地址:https://www.cnblogs.com/zle1992/p/7828597.html
Copyright © 2011-2022 走看看