检查树是否是二叉搜索树

时间:2014-11-22 13:46:27

标签: java binary-search-tree

我无法理解Java函数HERE(请滚动到页面的最后)如何检查树是否为BST,因为代码看起来不像使用min和最大的。 我也复制粘贴代码

/** 
 Tests if a tree meets the conditions to be a 
 binary search tree (BST). Uses the efficient 
 recursive helper. 
*/ 
public boolean isBST2() { 
 return( isBST2(root, Integer.MIN_VALUE, Integer.MAX_VALUE) ); 
}
/** 
  Efficient BST helper -- Given a node, and min and max values, 
  recurs down the tree to verify that it is a BST, and that all 
  its nodes are within the min..max range. Works in O(n) time -- 
  visits each node only once. 
*/ 
private boolean isBST2(Node node, int min, int max) { 
  if (node==null) { 
    return(true); 
  } 
  else { 
   // left should be in range  min...node.data 
    boolean leftOk = isBST2(node.left, min, node.data);

    // if the left is not ok, bail out 
    if (!leftOk) return(false);

    // right should be in range node.data+1..max 
    boolean rightOk = isBST2(node.right, node.data+1, max);

    return(rightOk); 
  } 
} 

2 个答案:

答案 0 :(得分:1)

当且仅当顺序遍历的节点是单调的时,树才是BST。想到这一点的最简单方法是,如果根的值为 n ,那么左侧分支也应该是一个BST,其节点最多为 n ,并且右侧应为BST,其节点至少为 n 。如果满足这些条件,那么整个树就是BST。

这正是您的代码几乎所做的。它检查树是否是给定最小值的给定最小值的BST。它通过查看具有值 data 的根节点来递归调用自身,然后检查左侧分支是否是BST,其节点都不超过 data ,并且右侧分支是BST,其节点都不小于 data

但实际上它并没有做到这一点......它错过了最小/最大检查!也许你应该自己添加它?这是家庭作业吗?

添加它的地方就在这里:

if (node==null) { 
  return(true); 
}

如果node!=null ...

,您只需要几个额外的条件

答案 1 :(得分:0)

boolean checkBST(Node root) {
    return  c(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

boolean c(Node n, int s, int b) {
    return n == null || (n.data > s && n.data < b && c(n.left, s, n.data) && c(n.right, n.data, b));
}
相关问题