1

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

Shane
  • 61
  • 2
  • 5

3 Answers3

4

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); 
Péter Török
  • 114,404
  • 31
  • 268
  • 329
SJuan76
  • 24,532
  • 6
  • 47
  • 87
  • Also, when node1 == null && node2 == null you should return true – SJuan76 Mar 21 '11 at 20:54
  • I still get the same result. When I call the method on an identical tree it still gives me false. – Shane Mar 21 '11 at 21:06
  • Have you checked the equals() method of your node? Did you create two nodes that should be equal and check that node1.equals(node2)? – SJuan76 Mar 21 '11 at 22:26
2

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)

z7sg Ѫ
  • 3,153
  • 1
  • 23
  • 35
  • 1
    Ah, the IntTreeNode class I was given didn't have this in there. Put it in and it works like a charm! I tried everything from using the equals() method for objects to compare the data in each, then comparing the left and right nodes to a massive if/else block. Thank you so much! – Shane Mar 22 '11 at 05:27
0
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);
}
andrucz
  • 1,971
  • 2
  • 18
  • 30