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

来源:互联网 发布:t恤印花 知乎 编辑:程序博客网 时间:2024/05/18 02:32
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出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);        }    }}
阅读全文
0 0
原创粉丝点击