You are on page 1of 15

QUESTION

02

Write an algorithm and program for demonstrating whether


two binary trees A and B are similar. Illustrate your algorithm
with sample trees of minimum depth 4.
ALGORITHM

 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;
};

struct node* inorder(struct node *tree1,struct node *tree2)


{
if(tree1->left&&tree2->left)
inorder(tree1->left,tree2->left);
if(tree1->data!=tree2->data)
{
count=1;
return;
}
if(tree1->right&&tree2->right)
inorder(tree1->right,tree2->right);
}
struct node* getnode()

struct node *root=NULL,*p,*cur,*parent;

char ch='s';

while(ch=='s')

p=(struct node*)malloc(sizeof(struct node));

printf("\nEnter the data:");

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

 Tree 1 and tree 2 are traversed inorder



10=10,15=15
30

13=13
 20=20,30=30 20 32

 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

You might also like