Determine if Two Trees are Identical
PROBLEM :
Given two binary trees, your task is to find if both of them are identical or not .
Input:
The task is to complete the method which takes 2 argument, the roots r1 and r2 of the Binary Trees. The struct Node has a data part which stores the data, pointer to left child and pointer to right child.
There are multiple test cases. For each test case, this method will be called individually.
Output:
The function should return true if both trees are identical else false.
Constraints:
1 <=T<= 30
1 <=Number of nodes<= 100
1 <=Data of a node<= 1000
example : given below two trees are identical so function should return true
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/* A binary tree node
struct node
{
int data;
struct Node* left, * right;
}; */
/* Should return true if trees with roots as r1 and
r2 are identical */
bool isIdentical(Node *r1, Node *r2)
{
if(r1==NULL&&r2==NULL)
return true ;
if(r1==NULL||r2==NULL)
return false ;
if(r1->data==r2->data)
return(isIdentical(r1->left,r2->left)&&isIdentical(r1->right,r2->right)) ;
else
return false ;
}
---------------------------------------------------------------------------------
Given two binary trees, your task is to find if both of them are identical or not .
Input:
The task is to complete the method which takes 2 argument, the roots r1 and r2 of the Binary Trees. The struct Node has a data part which stores the data, pointer to left child and pointer to right child.
There are multiple test cases. For each test case, this method will be called individually.
Output:
The function should return true if both trees are identical else false.
Constraints:
1 <=T<= 30
1 <=Number of nodes<= 100
1 <=Data of a node<= 1000
example : given below two trees are identical so function should return true
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/* A binary tree node
struct node
{
int data;
struct Node* left, * right;
}; */
/* Should return true if trees with roots as r1 and
r2 are identical */
bool isIdentical(Node *r1, Node *r2)
{
if(r1==NULL&&r2==NULL)
return true ;
if(r1==NULL||r2==NULL)
return false ;
if(r1->data==r2->data)
return(isIdentical(r1->left,r2->left)&&isIdentical(r1->right,r2->right)) ;
else
return false ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment