剑指offer 二叉树的后续遍历序列

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

这题不难,今天想到一个比较好的递归的解法。

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

    public boolean isGood(int[] seq, int s, int e){
        if(s==e) return true;
        int root = seq[e];
        int idx = e-1;
        while(idx>=s){
            if(seq[idx] < root){
                break;
            }else{
                idx--;
            }
        }
        if(idx < s){
            return isGood(seq, s, e-1);
        }else{
            for(int i = s; i<idx; i++){
                if(seq[i] > root){
                    return false;
                }
            }
            return isGood(seq, s, idx) && isGood(seq, idx+1, e);
        }

    }

}

猜你喜欢

转载自blog.csdn.net/crystal_zero/article/details/73502353
今日推荐