剑指Offer:二叉搜索树的后序遍历序列【33】
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
题目分析
Java题解
package tree; import java.util.ArrayList; public class VerifySquenceOfBST { public static boolean VerifySquenceOfBST(int [] sequence) { if(sequence.length<=0) return false; ArrayList<Integer> al = new ArrayList<>(); for(int s:sequence) al.add(s); return VerifySquenceOfBSTCore(al); } public static boolean VerifySquenceOfBSTCore(ArrayList<Integer> sequence) { if(sequence.size()<=0) return true; //取出序列最后一个元素 int mid = sequence.get(sequence.size()-1); //System.out.println(mid); ArrayList<Integer> left = new ArrayList<>(); ArrayList<Integer> right = new ArrayList<>(); //扫描左子树 int i = 0; for(;i<sequence.size()-1;i++) { if(sequence.get(i)>mid) break; left.add(sequence.get(i)); } int j = i; //扫描右子树 for(;j<sequence.size()-1;j++) { if(sequence.get(j)<mid) return false; right.add(sequence.get(j)); } //判断左子树 boolean le = true; le = VerifySquenceOfBSTCore(left); boolean ri = true; ri = VerifySquenceOfBSTCore(right);
//判断左右子树是否均满足 return le&&ri; } public static void main(String[] args) { int[] arr ={5,7,6,9,11,10,8}; System.out.println(VerifySquenceOfBST(arr)); } }