微软算法100题09 判断整数序列是不是二元查找树的后序遍历结果

9. 判断整数序列是不是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/
6 10
/ /
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。

思路:如果一个数组为BST的后序遍历结果 则最后一个元素必然为该BST的根节点 因为BST的特性是左子树必然全部小于根节点,右子树全部大于根节点,则我们可以从数组倒数第二个元素开始往前遍历,直到找到第一个小于根节点的元素,则从数组第一个元素到该元素之间的所有元素为左子树(包含),该元素到根节点元素之间的元素为右子树(不包含),先分别遍历左子树元素和右子树元素,如果左子树中有大于根节点的元素,则不符合BST的定义,同理如果右子树元素中有小于根节点的元素,也不符合BST的定义,如果验证通过,则用上述逻辑递归校验左子树和右子树

 1 package com.rui.microsoft;
 2 
 3 import java.util.Arrays;
 4 
 5 public class Test09_IsBSTByPostOrder {
 6 
 7     public static void main(String[] args) {
 8         //int[] origin = {5,7,6,9,11,10,8};
 9         int[] origin = {5,6,7,8,9,10,11};
10         //int[] origin = {7,4,6,5};
11         boolean flag = isBST(origin);
12         System.out.println(flag);
13     }
14     
15     public static boolean isBST(int[] input){
16         boolean flag = false;
17         int n = input.length;
18         //n==0 means current tree is empty
19         if(n==1 || n==0) return true;
20         else{
21             //the last element in the post-order query array must be the root node
22             int root = input[n-1];
23             int line = n - 2;
24             //search the dividing line between left tree and right tree of the root
25             while(input[line] > root && line >= 0){
26                 line--;
27             }
28             //now the pointer line should be pointing to the last node of the leaf tree
29             
30             int[] left = Arrays.copyOfRange(input, 0, line+1);
31             int[] right = Arrays.copyOfRange(input, line+1, n-1);
32             
33             if(!checkLeft(left, root) || !checkRight(right, root)) return false;
34             if(isBST(left) && isBST(right))return true;
35         }
36         
37         return flag;
38     }
39     
40     private static boolean checkLeft(int[] left, int root){
41         for(int i : left){
42             if(i > root) return false;
43         }
44         return true;
45     }
46     
47     private static boolean checkRight(int[] right, int root){
48         for(int i: right){
49             if(i < root) return false;
50         }
51         return true;
52     }
53 }
原文地址:https://www.cnblogs.com/aalex/p/4902293.html