此问题已经在这里有了答案:
这是我的代码:
public boolean isBST() {
return isBST(this.root);
}
private boolean isBST(BinaryNode<T> rootNode) {
if (rootNode == null) {
return false;
}
if (rootNode.isLeaf()) {
return true;
}
T left = null;
T right = null;
if (rootNode.hasLeftChild()) {
left = rootNode.getLeftChild().getData();
if (left.compareTo(rootNode.getData()) < 0) {
return this.isBST(rootNode.getLeftChild());
}
else {
return false;
}
}
if (rootNode.hasRightChild()) {
right = rootNode.getRightChild().getData();
if (right.compareTo(rootNode.getData()) > 0) {
return this.isBST(rootNode.getRightChild());
}
else {
return false;
}
}
return true;
}
此代码适用于简单的二叉树,但不适用于其他树。就像我有一棵这样的树:
5
/ \
3 6
/\
1 2
它甚至不会认为它应该标记为错误,因为2小于3并且在错误的位置。我的代码只检查左孩子的左孩子,而不检查内孩子的右孩子。我怎样做才能使代码以我编写的方式工作?如何修改?
该错误已解决
我认为您需要做的就是递归地看向左和向右,只有在错误的情况下才返回