简体   繁体   中英

Equals method to compare two tree's

just another slight problem. I must also create an equals method for my IntTree class which cycles through two tree's and compares the nodes. If all of the values in the tree are equal, then it returns true, otherwise it returns false. Here is the code I have so far:

private boolean equals(IntTreeNode node1, IntTreeNode node2){
    if ((node1 != null) || (node2 != null)){
        if (node1.equals(node2)){
            equals(node1.left, node2.left);
            equals(node1.right, node2.right);
            return node1.equals(node2);
        }
    }
    return false;
}

When I call this method on my Driver program to compare two tree's that are exactly alike (blah1.equals(blah2)), I get false. However, when I call blah1.equals(blah1) I get true... I'm not sure if my return statement is correct either

Why do you do two equals without handling the result?

I would change the inner if by just

return equals(node1.left, node2.left) && equals(node1.right, node2.right); 

I'm going to hazard a guess that you haven't overridden the equals method of IntTreeNode or haven't done it correctly.

I would do that something like this:

public boolean equals(Node other) {
    if (other == null ) return false;

    boolean valuesEqual = this.value == other.value;
    boolean leftEquals = this.left == null ? other.left == null : this.left.equals(other.left);
    boolean rightEquals = this.right == null ? other.right == null : this.right.equals(other.right);

    return valuesEqual && leftEquals && rightEquals;
}

And then to compare the two trees you can just call rootNode.equals(otherRootNode)

private boolean equals(IntTreeNode node1, IntTreeNode node2) {
    if (node1 == node2) {
        return true;
    }

    if (node1 == null || !node1.equals(node2)) {
        return false;
    }

    return equals(node1.left, node2.left) && equals(node1.right, node2.right);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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