题目描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
public class Solution { public boolean VerifySquenceOfBST(int [] sequence) { if(sequence.length == 0) return false; return IsTreeBST(sequence, 0, sequence.length-1); } public boolean IsTreeBST(int [] sequence,int start,int end ){ //if(end <= start) return true; int i = start; for (; i < end; i++) { if(sequence[i] > sequence[end]) break; } int j; for (j = i; j < end; j++) { if(sequence[j] < sequence[end]) return false; } boolean left=true; //根结点左子树不为空 if(i>0){ left=IsTreeBST(sequence, start, i-1); } boolean right=true; //根结点右子树不为空 if(j<end-1){ return IsTreeBST(sequence, i, end-1); } return left&&right; } }