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

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

解法是递归判断,先找根节点,划分左右子树递归求解。边界需要特殊考虑。

AC代码:

public class Solution {
    public boolean VerifySquenceOfBST(int[] sequence) {
        if(sequence == null || sequence.length <= 0)
            return false;
        
        int len  = sequence.length;
        
        return solve(sequence, 0, len-1);
        
    }
    
    public boolean solve(int[] sequence, int start, int end) {
        if(start == end)
            return true;
        int root = sequence[end];
        //System.out.println(root);
        int index = start;
        for(; index < end; index ++) {
            if(sequence[index] > root)
                break;
        }
        
        for(int j=index; j<end; j++) {
            if(sequence[j] < root)
                return false;
        }
        
        boolean left = true;
        if(index > start)
            left = solve(sequence, start, index-1);
        
        boolean right = true;
        if(index < end)
            right = solve(sequence, index, end-1);
        
        return  (left && right) ;
        
    }
}
原文地址:https://www.cnblogs.com/wxisme/p/5406498.html