23二叉搜索树的后序遍历序列

题目描述

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

Java实现

public class Solution {
    public boolean VerifySquenceOfBST(int[] sequence) {
        if (sequence == null || sequence.length == 0)
            return false;
        return VerifySquenceOfBST(sequence, 0, sequence.length - 1);
    }

    private boolean VerifySquenceOfBST(int[] sequence, int first, int last) {
        if (last - first <= 1)
            return true;
        int rootVal = sequence[last];
        int cutIndex = first;
        while (cutIndex < last && sequence[cutIndex++] < rootVal) ;
        for (int i = cutIndex; i < last; i++) {
            if (sequence[i] < rootVal)
                return false;
        }
        return VerifySquenceOfBST(sequence, first, cutIndex - 1) && VerifySquenceOfBST(sequence, cutIndex, last - 1);
    }
}

你可能感兴趣的:(23二叉搜索树的后序遍历序列)