Professional Documents
Culture Documents
02
Getdata:
Get the elements for binary tree 1 and binary tree 2.
tree1=getnode()
tree2=getnode()
To find whether tree1 and tree2 Similar:
Using inorder traversal, check whether the elements of tree1 and tree2 are
similar.
Initialising count=0
Inorder traversal:
inorder(tree1,tree2)
if(tree1->left&&tree2->left)
inorder(tree1->left,tree2->left)
if(tree1->data!=tree2->data)
Count=1
Return
end if
if(tree1->right&&tree2->right)
If count=1
Trees are not similar
Else if count =0
Trees are similar
end
PROGRAM
#include <stdio.h>
#include <stdlib.h>
int count=0;
struct node
{
int data;
struct node *left,*right;
};
char ch='s';
while(ch=='s')
scanf("%d",&p->data);
p->left=NULL;
p->right=NULL;
if(root==NULL)
{
if(p->data>parent->data)
{
parent->right=p;
}
else
{
parent->left=p;
} }
Example-1
Tree 1 55
30 60
20 32 57 65
15 62 70
10 13
55
Tree 2
30 60
20 32 57 65
15 62 70
10 13
TRACE
32=32
15
10 13
55=55 55
57=57,60=60
60
62=62
65=65 57 65
70=70 62 70
Since all the elements are similar here,count remains 0
Therefore TREES ARE SIMILAR
Example 2
Tree 1 55
30 60
20 32 57 65
15 62 70
10 13
Tree 2 55
30 60
22 32 57 65
15 62 70
10 13
Both trees will be traversed 55
10=10,13=13
30
15=15
20!=22 20 32
22
count becomes 1,and will be terminated from the
15
inorder() function.
10 13
Since count=1, TREES ARE NOT SIMILAR