微软口试100题_9
微软面试100题_9
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
package cn.emma.interview_9; public class Ex9 { public static boolean isBackOrder(int[] a,int left,int right){ int root = a[right]; if(left < right){ int i=left,j=right-1; while(a[i] < root){ i++; } while(a[j] > root){ j--; } if(i != j +1){ return false; }else{ return isBackOrder(a, left, j) && isBackOrder(a, i, right-1); } } return true; } public static void main(String[] args) { int[] a = {5,7,6,9,11,10,8}; System.out.println(isBackOrder(a, 0, a.length-1)); } }