0

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;
}  
Poindexter
  • 2,396
  • 16
  • 19
  • 1
    possible duplicate of [Determine if two binary trees are equal](http://stackoverflow.com/questions/1482822/determine-if-two-binary-trees-are-equal) – parapura rajkumar Jan 10 '12 at 16:15

4 Answers4

2

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
2

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.

Matt
  • 4,515
  • 5
  • 22
  • 29
1
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.

0
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

brain storm
  • 30,124
  • 69
  • 225
  • 393