简体   繁体   English

equals()方法在此二叉树上工作吗?

[英]Does the equals() method work on this Binary Tree?

I wrote a method that checks if two binary tree are equal. 我写了一个方法来检查两个二叉树是否相等。

Is this correct or is there a better way? 这是正确的还是有更好的方法?

public  boolean equal(BinaryNode t1, BinaryNode t2){  
    if(t1==null || t2==null)  
        return false;  
    else if(t1.element != t2.element)  
        return false;  
    else if(equal(t1.left,t2.left))   
        return false;  
    else if(equal(t1.right,t2.right))   
        return false;  
    else  
        return true;
}  

Don't ask us - write unit tests to prove that it's correct. 不要问我们-编写单元测试证明它是正确的。

Be sure to include all kinds of corner cases - I think there's at least one error since equals(null, null) will return false . 确保包括各种极端情况-我认为至少存在一个错误,因为equals(null, null)将返回false

The following is probably closer to the logic you're looking for, but is completely untested and was written in this text field: 以下内容可能更接近您要查找的逻辑,但完全未经测试,并且是在此文本字段中编写的:

if (t1==null && t2==null)
    return true;
if (t1.element != t2.element)
    return false;
return equal(t1.left, t2.left) && equal(t1.right, t2.right);

There are a lot of flaws in your current version. 当前版本中存在很多缺陷。

public boolean binaryTreeEquals(BinaryNode node1, BinaryNode node2)
{
    if(node1 == node2 == null)
        return true;
    if(node1.element == node2.element &&
        binaryTreeEquals(node1.left, node1.right) &&
        binaryTreeEquals(node2.left, node2.right)
        return true;
    else
        return false;
}

This code should work. 此代码应该起作用。 You're checking if node1 or node2 are null and then return false but if they both are then it's equal. 您正在检查node1node2是否为空,然后返回false,但如果两者都相等,则相等。

public boolean equals(BinaryNode root1, BinaryNode root2) {
    if (root1 == null || root2 == null) {
        return root1 == null && root2 == null;
    } else {
        return root1.data == root2.data
        && equals2(root1.left, root2.left)
        && equals2(root1.right, root2.right);
    }
}

Both the solutions above, do not cover the corner cases of one root being null and other is Not null 以上两种解决方案都没有涵盖一个根为null而另一个为非Not null

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

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