Click here to Skip to main content
15,888,337 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi i coded a function that checks two binary tree are equal or not

i dont know its correct or not please help!

Java
public static 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;

  }
Posted

1 solution

Firstly, I am not familiar with the class BinaryNode so I would guess it is your own.
The approach I would take is to make the class implement the equals method:

Java
public class BinaryNode {

    // stuff

    public int equals(Object obj) {
        if (this == obj) {
          return true;
        }
        if ( obj == null || !(obj instanceof BinaryNode)) {
            return false;
        }

        BinaryNode that = (BinaryNode)obj;
        if (this.element.equals(that.element)) {
            return false;
        }
        else if (this.left == null || this.left.equals(that.left)) {
            return false;
        }
        else if (this.right == null || this.right.equal(that.right)) {
            return false;
        }
        // must be the same
        return true;
    }

}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 10-Jan-12 15:00pm    
Sure, a 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900