戴璞微的博客

简单点!做事的动机简单点

剑指offer--二叉搜索树的后序遍历序列

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


思路:
二叉搜索树的性质:根节点大于左子树所有元素,小于右子数的所有元素。后序遍历的话,最后一个元素就为根节点root。若数组为null或者长度为0,则返回true,若数组基本有序(即所有元素已经是升序或降序),返回true,否则,找到划分左右子树的数组元素下标(sequence[i] < root && sequence[i+1] > root),之后判断下标属于[0,i]的子序列是否全小于root,[i,len-2]的子序列是否全大于root。


AC代码:

import java.util.Arrays;

public class Solution {
    public boolean VerifyLeftTree(int[] leftsequence , int root){
        boolean flag = true;
        for ( int i = 0 ; i < leftsequence.length ; i++){
            if ( leftsequence[i] >= root){
                flag = false;
                break;
            }
        }
        return flag;
    }

    public boolean VerifyRightTree(int[] rightsequence , int root){
        boolean flag = true;
        for ( int i = 0 ; i < rightsequence.length ; i++){
            if ( rightsequence[i] <= root){
                flag = false;
                break;
            }
        }
        return flag;
    }

    //判断sequence是否已经有序
    public boolean IsOrder(int [] sequence){
        //判断是否已经是升序
        int[] tmp = Arrays.copyOfRange(sequence, 0, sequence.length);
        Arrays.sort(tmp);
        boolean flag1 = true;
        for(int i = 0 ; i < sequence.length ; i++){
            if ( sequence[i] != tmp[i]){
                flag1 = false;
                break;
            }
        }

        //判断是否已经是降序
        int cnt = 0;
        boolean flag2 = true;
        for ( int i = tmp.length-1 ; i >= 0 ; i--){
            if ( sequence[cnt++] != tmp[i]){
                flag2 = false;
                break;
            }
        }

        boolean flag = flag1 || flag2;
        return flag;
    }

    public boolean VerifySquenceOfBST(int [] sequence) {
        int partition = 0;
        int len = sequence.length;
        if ( sequence == null || len == 0){
            return false;
        }

        int root = sequence[len-1];
        if ( IsOrder(sequence)){
            return true;
        }

        for ( int i = 0 ; i < len-1 ; i++){
            if (sequence[i] < root && sequence[i+1] > root){
                partition = i;
                break;
            }
        }

        int[] left = Arrays.copyOfRange(sequence, 0, partition+1);
        int[] right = Arrays.copyOfRange(sequence, partition+1, len-1);

        for ( int i = 0 ; i < left.length ; i++){
            System.out.print(left[i]+" ");
        }
        System.out.println();
        for ( int i = 0 ; i < right.length ; i++){
            System.out.print(right[i]+" ");
        }
        boolean leftflag = VerifyLeftTree(left,root);
        boolean rightflag = VerifyRightTree(right,root);
        boolean flag = leftflag & rightflag;
        return flag;
    }
}
阅读更多
版权声明:本文为博主原创文章,若需转载,请注明http://blog.csdn.net/qq_30091945 https://blog.csdn.net/qq_30091945/article/details/71072475
所属专栏: 剑指offer题解
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭