剑指offer系列之二十二:二叉搜索树的后续遍历序列

来源:互联网 发布:linux smp lock.h 编辑:程序博客网 时间:2024/06/04 23:34

题目描述

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

此题仍然是对二叉树遍历方法的考察,但是与直接对遍历方法的考察不太一样,因为这里的输入是后续遍历的序列,所以要判断该序列是否是某二叉树的后续遍历结果,关键在于找出根节点,根节点的左子树和根节点的右子树,然后继续对左子树和右子树进行判断,直到全部元素访问完毕。这里很显然是一个递归的过程。由于后续遍历是先访问双亲节点,接着访问左孩子,再访问右孩子,所以需要对每个节点的左右子树做进一步的判断。

明白思路后,可以写出如下的实现代码(已被牛客AC):

package com.rhwayfun.offer;public class VerifySequenceOfBiST {    public boolean VerifySquenceOfBST(int[] sequence) {        if(sequence.length <= 0) return false;        int rootVal = sequence[sequence.length - 1];        int i = 0;        for(; i < sequence.length - 1; i++){            if(sequence[i] > rootVal) break;        }        //拷贝左子树到一个新的数组        int[] leftTree = new int[i];        System.arraycopy(sequence, 0, leftTree, 0, i);        int j = i;        for(; j < sequence.length - 1; j++){            if(sequence[j] < rootVal) return false;        }        //拷贝右子树到一个新数组        int[] rightTree = new int[sequence.length - i - 1];        System.arraycopy(sequence, i, rightTree, 0, sequence.length - i - 1);        boolean verifyLeft = true;        if(i > 0){            verifyLeft = VerifySquenceOfBST(leftTree);         }        boolean verifyRight = true;        if(i < sequence.length - 1){            verifyRight = VerifySquenceOfBST(rightTree);        }        return verifyLeft && verifyRight;    }    public static void main(String[] args) {//      int[] sequence = new int[]{5,7,6,9,11,10,8};        int[] sequence = new int[]{7,4,6,5};        System.out.println(new VerifySequenceOfBiST().VerifySquenceOfBST(sequence));    }}
0 0
原创粉丝点击