1.数据的准备
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
2.使用数组的方式判断
/**
* use container
* @param head
* @return
*/
public static boolean isSearch1(Node head) {
if(head == null){
return true;
}
ArrayList<Node> nodes = new ArrayList<>();
in(head,nodes);
for (int i = 0; i < nodes.size() - 1; i++) {
if(nodes.get(i).value >= nodes.get(i + 1).value){
return false;
}
}
return true;
}
/**
* middle traversal
* @param head
* @param arr
*/
public static void in(Node head, ArrayList<Node> arr) {
if(head == null){
return;
}
in(head.left,arr);
arr.add(head);
in(head.right,arr);
}
3.不使用数组的方式实现
/**
* middle traversal
* @param head
* @param arr
*/
public static void in(Node head, ArrayList<Node> arr) {
if(head == null){
return;
}
in(head.left,arr);
arr.add(head);
in(head.right,arr);
}
/**
* prepare data Object
*/
public static class Info {
private int max;
private int min;
private boolean isSearch;
public Info(int mx,int mn,boolean isS){
max = mx;
min = mn;
isSearch = isS;
}
}
/**
* nonuse container
* @param head
* @return
*/
public static boolean isSearch2(Node head) {
if(head == null){
return true;
}
return process(head).isSearch;
}
/**
* core code
* @param head
* @return
*/
public static Info process(Node head) {
if(head == null){
return null;
}
// ====== prepare ======
Info leftInfo = process(head.left);
Info rightInfo = process(head.right);
int max = head.value, min = head.value;
boolean isSearch = true;
// ====== prepare end ======
//===== find the maximum and minimum ======
if(leftInfo != null){
max = Math.max(max,leftInfo.max);
}
if(rightInfo != null){
min = Math.min(min,rightInfo.min);
}
if(rightInfo != null){
max = Math.max(max,rightInfo.max);
}
if(leftInfo != null){
min = Math.min(min,leftInfo.min);
}
//===== find the maximum and minimum end ======
// ======= check =======
if(leftInfo != null){
if(leftInfo.max >= head.value || !leftInfo.isSearch){
isSearch = false;
}
}
if(rightInfo != null){
if(rightInfo.min <= head.value || !rightInfo.isSearch){
isSearch = false;
}
}
// ======= check end =======
return new Info(max,min,isSearch);
}
总结:
1.当左子树的值比当前节点大
2.当右子树的值比当前的节点小
3.以上两种情况可判断为不是搜索二叉树