/** * 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果,假设输入的数组的任意两个数字都互不相同 * @author Q.Yuan * */ public class JudgePostOrder { /** * * @param a 后序遍历结果 * @param low 序列的开始 * @param high 序列的结束 * @return */ public boolean isPostOrder(int[] a,int low,int high){ int root = a[high]; int leftEnd = low; //找到第一个比根节点大的值,其为右子树序列的开始 for(;leftEnd <= high - 1;leftEnd++){ if(a[leftEnd] > root){ break; } } leftEnd--; //判断左子树的值是否都小于根节点的值 for(int i = low;i <= leftEnd;i++ ){ if(a[i] > root){ return false; } } //判断右子树的值是否都大于根节点的值 for(int j = leftEnd + 1;j <= high - 1;j++){ if(a[j] < root){ return false; } } boolean left = true ; boolean right = true; //如果有左子树 if(low <= leftEnd){ left = isPostOrder(a, low, leftEnd); } //如果有右子树 if(leftEnd < high - 1){ right = isPostOrder(a, leftEnd + 1, high - 1); } return left && right; } public static void main(String[] args) { JudgePostOrder jpo = new JudgePostOrder(); // int[] a = {5,7,6,9,11,10,8}; // int[] a = {1,2,3,8,7,6,5}; int[] a = {1,2,3,5}; System.out.println(jpo.isPostOrder(a, 0, a.length - 1)); } }