In this blog, we're going to cover Symmetric Tree and Identical Tree problems. These are quite similar problems, in the Symmetric tree we are provided with a single tree, but for checking identical trees we're provided two trees.
What is a Symmetric Tree?
A tree is called symmetric if it contains a mirror image of itself when divided from the center(root). This means that the left portion of the tree should be symmetric to the right portion of the tree.
Example of a Symmetric Tree:
What are Identical Trees?
Two trees are said to be identical when they have the same data and the arrangement of data is also the same in them.
Example of Identical Trees:
In symmetric trees, the left portion of the tree is compared to the right portion of the tree. Whereas in the case of identical trees the left portion of one tree is compared with the left portion of another tree similarly, the right portion of one tree is compared with the right portion of another tree.
Symmetric Tree
// utility function bool is_symmetric(node *root1,node *root2) { if(root1==NULL && root2==NULL) return true; if(root1 && root2 && root1->data==root2->data) return is_symmetric(root1->left,root2->right) && is_symmetric(root1->right,root2->left); return false; } // main function bool symmetric(node *root) { return is_symmetric(root,root); }
Identical Trees
// main function
bool isIdentical(Node *r1, Node *r2)
{
if(!r1 && !r2)
return true;
if(r1 && r2)
{
if(r1->data==r2->data)
return ( isIdentical(r1->left,r2->left) && isIdentical(r1->right,r2->right));
}
return false;
}
I hope this tutorial helped you!Happy Coding!
Comments
Post a Comment
Your Feedback Will Help Us To Improve...