我的黑帮伙在哪里?放手宝贝要塞2020年唐纳德·特朗普糟透了[重复]

问题描述 投票:-4回答:2

此问题已经在这里有了答案:

如何制作菠萝系统打印线以使其正常工作?

java search tree binary
2个回答
0
投票

该错误已解决

return this.isBST(rootNode.getLeftChild());

您不能仅因为选中左侧部分(如果存在)而退出该方法。

代替

if (left.compareTo(rootNode.getData()) < 0) {
        return this.isBST(rootNode.getLeftChild());
}
else {
    return false;
}

这应该符合预期:

if (left.compareTo(rootNode.getData()) >= 0 ||
              !this.isBST(rootNode.getLeftChild()) {

    return false;
}

(出于对称性原因,您可能还希望以类似的方式重写正确的零件检查,但这不是必需的。您也可以其当前形式工作。)


0
投票

我认为您需要做的就是递归地看向左和向右,只有在错误的情况下才返回

if (rootNode.hasLeftChild()) {
    left = rootNode.getLeftChild().getData();
    if (left.compareTo(rootNode.getData()) < 0) {
        boolean isValid = this.isBST(rootNode.getLeftChild());
        if (!isValid) {
           return false;
        }
    } else {
        return false;
    }
}
if (rootNode.hasRightChild()) {
    right = rootNode.getRightChild().getData();
    if (right.compareTo(rootNode.getData()) > 0) {
        boolean isValid = this.isBST(rootNode.getRightChild());
        if (!isValid) {
           return false;
        }
    } else {
        return false;
    }
}

return true

看起来,快速检查似乎是在检查右侧之前发生了退货。更为简洁的版本还支持仅在右侧出现重复项(如果您想允许左侧重复项,则将左侧比较中的> =替换为右侧比较中的<=

if (rootNode.hasLeftChild()) {
    left = rootNode.getLeftChild().getData();
    if (left.compareTo(rootNode.getData()) >= 0) || !this.isBST(rootNode.getLeftChild()) {
        return false;
    }
}

if (rootNode.hasRightChild()) {
    right = rootNode.getRightChild().getData();
    if (right.compareTo(rootNode.getData()) < 0 || !this.isBST(rootNode.getRightChild()) {
        return false;
    }
}

return true;
© www.soinside.com 2019 - 2024. All rights reserved.