题目链接

牛客网

题目描述

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

解题思路

找到左右子树的位置,再用递归遍历左右子树

public class Solution {
   
    public boolean VerifySquenceOfBST(int [] sequence) {
   
        if (sequence==null || sequence.length==0) return false;
        return verify(sequence, 0, sequence.length-1);
    }
    private boolean verify(int[] sequence, int first, int last) {
   
        if (last-first<=1) return true;
        int rootVal = sequence[last], cutIndex = first;
        while (cutIndex<last && sequence[cutIndex]<=rootVal) cutIndex++;
        // 找到左右子树的切分位置
        for (int i=cutIndex;i<last;i++) 
            if (sequence[i] < rootVal) return false;
        // 检查左右子树
        return verify(sequence, first, cutIndex-1) && verify(sequence, cutIndex+1, last);
    }
}