开发者

Equals method to compare two tree's

just another sligh开发者_如何学Got 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜