Can anyone explain why I am getting the output twice here?
# include<iostream>
# include<conio.h>
# include <stdio.h>
using namespace std;
struct tree
{
int data;
struct tree * left;
struct tree * right;
};
struct tree * insert(struct tree * root,int value)
{
if (root==NULL)
{
struct tree * node= (struct tree *)malloc(sizeof(struct tree));
node->data=value;
node->right=NULL;
node->left=NULL;
return node;
}
else if(root->data > value )
root->left=insert(root->left,value);
else
root->right=insert(root->right,value);
}
int same_tree(struct tree * root1, struct tree* root2)
{
if((root1==NULL && root2!=NULL) || (root1!=NULL && root2==NULL))
{
cout << " tree are not equal \n";
return -1;
}
if(root1 && root2)
{
same_tree(root1->left,root2->left);
if(root1->data!=root2->data)
{
cout << "tree not equal \n";
return -1;
}
same_tree(root1->right,root2->right);
}
}
int main()
{
struct tree * root=NULL;
root= insert(root,8);
insert(root,6);
insert(root,7);
insert(root,5);
insert(root,1);
insert(root,20);
insert(root,15);
struct tree * root2=NULL;
root2= insert(root2,8);
insert(root2,6);
insert(root2,7);
insert(root2,5);
insert(root2,1);
insert(root2,20);
insert(root2,18);
int j= same_tree(root,root2);
if(j==-1)
cout << " tree not eqqual \n";
else
cout << "tree are equal\n";
getch();
return 0;
}
The program is written to compare if two tree are same ( in the same hierarchial structure and data they contain) . The two tree i am comparing here is passed from main (root and root2).
In case of equal tree i get the O/o as “tree are equal” once . But in case tree are not equal i get an o/p “tre not equal ” and in next line as “tree are equal ” . I am unable to decipher Why ? I have written down the entire program so that anyone can copy paste and run it on their system . I guess The problem lies somewhere in recursive call of same_tree but where and why is something i am not getting
When comparing the trees you only return -1 (error) if the left node differs. You just ignore the right nodes. Also, if your trees only differ on the right side your same_tree does not return a value at all. I’m actually surprised this compiled at all.
If you look at your same_tree closely you will see that it checks if only one of the let/right is null and then if non are null. However, if they are both null you just fall through. You also ignore the return value at many points.
Say you have two roots, each with value 5 and one of them has left 7 while the other has left 8. Now when entering the same_tree you will compare the lefts which will front that that are different. However, the return value is ignored and you will continue with comparing the root value (both 5) and since they are same you will not return the error code and your main method will think every thing is fine and dandy and print that they are equal.