zoukankan      html  css  js  c++  java
  • 剑指Offer:二叉搜索树的后序遍历序列【33】

    剑指Offer:二叉搜索树的后序遍历序列【33】

    题目描述

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

    题目分析

    Java题解

    package tree;
    
    import java.util.ArrayList;
    
    public class VerifySquenceOfBST {
    
    
        public static boolean VerifySquenceOfBST(int [] sequence) {
            if(sequence.length<=0)
                    return false;
           ArrayList<Integer> al = new ArrayList<>();
           for(int s:sequence)
               al.add(s);
           return VerifySquenceOfBSTCore(al);
        }
    
    
    
        public static boolean VerifySquenceOfBSTCore(ArrayList<Integer> sequence) {
            if(sequence.size()<=0)
                return true;
    
            //取出序列最后一个元素
            int mid = sequence.get(sequence.size()-1);
            //System.out.println(mid);
            ArrayList<Integer> left = new ArrayList<>();
            ArrayList<Integer> right = new ArrayList<>();
            //扫描左子树
            int i = 0;
            for(;i<sequence.size()-1;i++)
            {
                if(sequence.get(i)>mid)
                    break;
                left.add(sequence.get(i));
            }
            int j = i;
            //扫描右子树
            for(;j<sequence.size()-1;j++)
            {
                if(sequence.get(j)<mid)
                    return false;
                right.add(sequence.get(j));
            }
    
            //判断左子树
            boolean le = true;
            le = VerifySquenceOfBSTCore(left);
            boolean ri = true;
            ri = VerifySquenceOfBSTCore(right);
         //判断左右子树是否均满足 return le&&ri; } public static void main(String[] args) { int[] arr ={5,7,6,9,11,10,8}; System.out.println(VerifySquenceOfBST(arr)); } }

      

  • 相关阅读:
    PhysX3 User Guide 04 Rigid Body Dynamics
    PhysX3 User Guide 05 Scene Queries
    PhysX3 User Guide 01 基础
    error C2061: syntax error : identifier '__RPC__out_xcount_part'
    vim中替换字符串
    Linker Tools Warning LNK4098
    PhysX3 User Guide 03 Joint
    【转】C RunTime Library 暨 深入理解编译选项的含义 04
    不足
    tortoiseSVN Check out正常但Show Log时 Go Offline
  • 原文地址:https://www.cnblogs.com/MrSaver/p/9283261.html
Copyright © 2011-2022 走看看