【牛客网】24.二叉搜索树的后序遍历序列
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同
package leetcode; public class L23SequenceOFBST { public boolean VerifySquenceOfBST(int[] sequence) { if(sequence==null)return false; int len = sequence.length; if(len<=0)return false; if(len==1)return true; return VerifySquenceOfBSTCore(sequence, 0,len-1); } private boolean VerifySquenceOfBSTCore(int[] sequence,int start, int len) { int root=sequence[len]; int i; for(i=start;i<len;i++){ if(sequence[i]>root) break; } int j; for(j=i;j<len;j++){ if(sequence[j]<root) return false; } boolean left=true; if(i>start){ left=VerifySquenceOfBSTCore(sequence,start,i-1); } boolean right=true; if(len-i>1){ right=VerifySquenceOfBSTCore(sequence,i,len-1); } return left&&right; } public static void main(String[] args) { int[] seq={7,4,6,5}; L23SequenceOFBST l23= new L23SequenceOFBST(); System.out.println(l23.VerifySquenceOfBST(seq)); int [] seq2={5,7,6,9,11,10,8}; System.out.println(l23.VerifySquenceOfBST(seq2)); } }