Implement a function to check if a binary tree is a binary search tree
判断一个二叉树是否是BST
思路:
1)中序遍历二叉树,把结果放在一个数组里。然后判断这个数组是否递增
2)在上一种方法的基础上优化,无需用到数组。在中序遍历时与上一个数比较,判断是否恒递增
3)我最喜欢的方法:min max的方法,限定每一个元素的上下限,如果超出范围则为false
参考LeetCode原题:http://blog.youkuaiyun.com/fightforyourdream/article/details/14444883
package Tree_Graph;
import CtCILibrary.TreeNode;
public class S4_5 {
// =============================== checkBST 方法1,中序遍历建数组
public static int index = 0;
public static boolean checkBST(TreeNode root, int size) {
int[] A = new int[size];
copyBST(root, A);
for(int i=1; i<A.length; i++) {
if (A[i] <= A[i-1]) {
return false;
}
}
return true;
}
public static void copyBST(TreeNode root, int[] A) {
if (root == null) {
return;
}
copyBST(root.left, A);
A[index++] = root.data;
copyBST(root.right, A);
}
// =============================== checkBST 方法2,中序遍历但仅保留last变量
public static int last = Integer.MIN_VALUE;
public static boolean checkBST2(TreeNode root) {
if(root == null) {
return true;
}
if( !checkBST2(root.left) ) { // 检测左子树
return false;
}
if(root.data <= last) { // 检查当前节点,如果有序则必然比last大
return false;
}
last = root.data; // 更新last节点
if( !checkBST2(root.right) ) { // 检查右子树
return false;
}
return true;
}
// =============================== checkBST 方法3,Min-Max
// Time: O(N), space: O(logN)
public static boolean checkBST3(TreeNode root) {
return checkBSTRec(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public static boolean checkBSTRec(TreeNode root, int min, int max) {
if (root == null) {
return true;
}
// 当前节点非BST
if(root.data<=min || root.data>max) {
return false;
}
// 左子树或者右子树非BST
if( !checkBSTRec(root.left, min, root.data) || !checkBSTRec(root.right, root.data, max)) {
return false;
}
return true;
}
public static void main(String[] args) {
int[] array = {3, 5, 6, 10, 13, 15};
// int[] array = {3, 5, 6};
TreeNode node = TreeNode.createMinimalBST(array);
node.print();
System.out.println(checkBST(node, array.length));
System.out.println(checkBST2(node));
System.out.println(checkBST3(node));
}
}