简体   繁体   English

如何检查二叉搜索树是否完美平衡?

[英]How to check if a Binary Search Tree is Perfectly Balanced?

I have this homework problem and I have completed all methods except this one, isPerfectlyBalanced() . 我有这个作业问题, isPerfectlyBalanced()方法isPerfectlyBalanced()之外,我已经完成了所有方法。

All my tests pass except one that should return false but instead returns true . 我所有的测试都通过了,除了应该返回false而是返回true I have attached my current code and the test that is failing. 我已附加了当前代码和失败的测试。 Any description on how to go about this or even let me know where my code is wrong is appreciated! 对此的任何描述,甚至让我知道我的代码出了问题的地方,都表示赞赏!

private boolean isPerfectlyBalanced(Node node) {

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

    if(size(node.left) == size(node.right)) {
        return true;
    }
    isPerfectlyBalanced(node.left);
    isPerfectlyBalanced(node.right);
    return false;

}


public boolean isPerfectlyBalancedS() {
    // TODO
    if (root == null) {
        return true;
    }
    return isPerfectlyBalanced(root);

}

Here is my test that is failing: 这是我的测试失败:

assertFalse(set.isPerfectlyBalancedS());

Thank you! 谢谢!

My size method: 我的尺寸方法:

private int size(Node node){
    if (node == null){
        return 0;
    } else {
        return (size(node.left) + 1 + size(node.right));
    }
}
public int size() {
    // TODO
    return size(root);
}

On the last line of the first method, you probably want to do this: 在第一种方法的最后一行,您可能想要执行以下操作:

return (isPerfectlyBalanced(node.left) && isPerfectlyBalanced(node.right));

instead of 代替

isPerfectlyBalanced(node.left);
isPerfectlyBalanced(node.right);
return false;

In your code, you dismiss the result of the isPerfectlyBalanced on the subtrees and always return false. 在您的代码中,您忽略了子isPerfectlyBalanced的结果,并且始终返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM