import java.util.ArrayList;/** * 判断树是否为搜索二叉树 */public class Code02_IsBST { public static class Node { public int value; public Node left; public Node right; public Node(int data) { this.value = data; } } public static boolean isBST1(Node head) { if (head == null) { return true; } ArrayList<Node> arr = new ArrayList<>(); in(head, arr); for (int i = 1; i < arr.size(); i++) { if (arr.get(i).value <= arr.get(i - 1).value) { return false; } } return true; } public static void in(Node head, ArrayList<Node> arr) { if (head == null) { return; } in(head.left, arr); arr.add(head); in(head.right, arr); } // ***************************************************************************** /** * 主函数 * @param head * @return */ public static boolean isBST2(Node head) { // 在这里处理空,将下层的空放在这里处理 if (head == null) { return true; } return process(head).isBST; } /** * 信息体定义 */ public static class Info { public boolean isBST; public int max; public int min; public Info(boolean i, int ma, int mi) { isBST = i; max = ma; min = mi; } } /** * 递归,所有过程一视同仁,必须返回信息体Info * @param x * @return */ public static Info process(Node x) { // base case 对于节点为空时,如果不知道如何设置信息体中的值,可以返回空,然后在上游来处理这个空null;最大值和最小值知道如何设置,返回空 if (x == null) { return null; } // 向左右树索取信息体信息 Info leftInfo = process(x.left); Info rightInfo = process(x.right); // 加工自己的信息体内容 // 1、加工 Info-max int max = x.value; // 首先设置自己值为最大值 if (leftInfo != null) { // 如果左树不为空,将左树中的最大值和当前max比较 max = Math.max(max, leftInfo.max); } if (rightInfo != null) { // 如果右树不为空,将右树中的最大值和当前max比较 max = Math.max(max, rightInfo.max); } // 2、加工 Info-min 最小值 int min = x.value; if (leftInfo != null) { min = Math.min(min, leftInfo.min); } if (rightInfo != null) { min = Math.min(min, rightInfo.min); } // 3、加工 Info-isBST,这时候由于null是没有判断的,放在上层判断,因此要充分考虑为空的情况。 boolean isBST = true; //先假定是搜索二叉树,然后判断以下条件是否违反,违反了重置isBST if (leftInfo != null && !leftInfo.isBST) { isBST = false; } if (rightInfo != null && !rightInfo.isBST) { isBST = false; } if (leftInfo != null && leftInfo.max >= x.value) { isBST = false; } if (rightInfo != null && rightInfo.min <= x.value) { isBST = false; } return new Info(isBST, max, min); } //#########################对数器############################################## // for test public static Node generateRandomBST(int maxLevel, int maxValue) { return generate(1, maxLevel, maxValue); } // for test public static Node generate(int level, int maxLevel, int maxValue) { if (level > maxLevel || Math.random() < 0.5) { return null; } Node head = new Node((int) (Math.random() * maxValue)); head.left = generate(level + 1, maxLevel, maxValue); head.right = generate(level + 1, maxLevel, maxValue); return head; } public static void main(String[] args) { int maxLevel = 4; int maxValue = 100; int testTimes = 1000000; for (int i = 0; i < testTimes; i++) { Node head = generateRandomBST(maxLevel, maxValue); if (isBST1(head) != isBST2(head)) { System.out.println("Oops!"); } } System.out.println("finish!"); }}