Wednesday, February 23, 2011

Java program to compare two binary trees


Algorithm:

   1. If roots of boths trees are null, then the trees are same (stopping condition for the recursion).
   2. If
       - the data in the roots are same &
       - the left subtrees are same &
       - the right subtrees are same
        Then the trees are same
    Else
        -trees are not same
        


public boolean compareTree(TreeNode root1,TreeNode root2)
{
if(root1==null && root2==null )
{
return true;
}

Comparable data1,data2;
data1=(Comparable)root1.data;
data2=(Comparable)root2.data;

if(data1.compareTo(data2)==0 && compareTree(root1.left,root2.left)
     && compareTree(root1.right,root2.right))
{
return true;
}
else
return false;


}

No comments: