Topic 4.5:Implement a function to check if a binary tree is a binary search tree.
方法0:Do an in-order traversal, copy the elements to an array, check to see if the array is sorted. Takes up a bit of extra memory. But we find that the array is not necessary, we never use it other than to compare an element to the previous element. So just track the last element we saw and compare.
方法1:Do an in-order traversal, track the last element we saw and compare it as we go.
方法2:keep min and max, and recursive. Time:O(N), best we can do, since we must touch all N nodes. Space O(logN). 这个方法很诡异,问到了再看下。
//记住:这是中序遍历,下面三步的顺序是不能变的,左根右,变了结果就不同;其实是一种递归(即一种堆栈),从最左边最下面的开始看起
public class c4_5 {
public static Integer last_printed = null;
public static boolean checkBST(TreeNode n) {
if (n == null) {
return true;
}
if (!checkBST(n.left)) {
return false;
}
if (last_printed != null && n.data <= last_printed) {
return false;
}
last_printed = n.data;//这一步是关键,由它给last_printed初始值,很神奇
if (!checkBST(n.right)) {
return false;
}
return true;
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TreeNode node = TreeNode.createMinimalBST(array);
System.out.println(checkBST(node));
}
}
//结果
true