4.5

Topic 4.5:Implement a function to check if a binary tree is a binary search tree.

方法0Do 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.

方法1Do an in-order traversal, track the last element we saw and compare it as we go.

方法2keep 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



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值