给定一棵二叉树的头节点head,返回这颗二叉树是不是搜索二叉树
搜索二叉树定义:左树所有结点比头结点小,右树所有结点比头结点大,每颗子树都如此。
根据二叉树的递归套路,直接得出每颗子树需要返回的信息就是:
整颗子树是否是搜索二叉树
整颗子树的最大值
整颗子树的最小值
比较简单,如果有不了解可以看看这篇文章——二叉树的递归套路——最大二叉搜索子树大小
接下来直接看代码叭:
package com.harrison.class08; import java.util.ArrayList; public class Code06_IsBST { public static class Node { public int value; public Node left; public Node right; public Node(int data) { this.value = data; } } public static class Info{ public boolean isBST; public int max; public int min; public Info(boolean is,int ma,int mi) { isBST=is; max=ma; min=mi; } } public static Info process1(Node head) { if(head==null) { return null; } Info leftInfo=process1(head.left); Info rightInfo=process1(head.right); int max=head.value; int min=head.value; if(leftInfo!=null) { max=Math.max(max, leftInfo.max); min=Math.min(min, leftInfo.min); } if(rightInfo!=null) { max=Math.max(max, rightInfo.max); min=Math.min(min, rightInfo.min); } boolean isBST=false; if( (leftInfo==null?true:leftInfo.isBST) && (rightInfo==null?true:rightInfo.isBST) && (leftInfo==null?true:leftInfo.max<head.value) && (rightInfo==null?true:rightInfo.min>head.value) ) { isBST=true; } return new Info(isBST, max, min); } public static boolean isBST1(Node head) { if(head==null) { return true; } return process1(head).isBST; } public static void in(Node head, ArrayList<Node> arr) { if (head == null) { return; } in(head.left, arr); arr.add(head); in(head.right, arr); } public static boolean isBST2(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 Node generateRandomBST(int maxLevel,int maxValue) { return generate(1, maxLevel, maxValue); } 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!"); } }