我无法理解Java函数HERE(请滚动到页面的最后)如何检查树是否为BST,因为代码看起来不像是使用最小和最大。 我这里复制粘贴代码以及检查一棵树是否是二叉搜索树
/**
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);
}
}
代码isBST2()方法:P。这只是检查最小最大条件是错过了。 – Andy897 2014-11-22 13:51:17
“一个更好的解决方案只查看每个节点一次,诀窍是编写一个实用辅助函数isBSTRecur(struct node * node,int min,int max),它遍历树中的最小和最大允许值,它看起来每个节点只有一次,最小值和最大值的初始值应该是INT_MIN和INT_MAX--它们从那里缩小。“ – DavidPostill 2014-11-22 13:52:52
@DavidPostill虽然这里的语法是C,但不是Java。 – 2014-11-22 13:55:45