Write a program to check that the left sub-tree of an binary tree (Not BST) is mirror image of its right sub-tree.
#include <iostream>
using namespace std;
// creation of the nodes
struct Tree
{
char data;
Tree *left;
Tree *right;
Tree(char data)
{
this -> data = data;
left = NULL;
right = NULL;
}
};
// function to check the mirror image, and it will return true and false.
bool mirrorBt(Tree *root_n1, Tree *root_n2){
// if it is mirror
if(!root_n1 && !root_n2){
return true;
}
else{
if(root_n1 && root_n2){
// check that the mirror image of the subtree found or not.
if(root_n1 -> data == root_n2 -> data){
return mirrorBt(root_n1 -> left, root_n2 -> right) &&
mirrorBt(root_n1 -> right, root_n2 -> left);
}
}
return false;
}
}
int main() {
// add elements to the tree
Tree *root = new Tree('1');
root -> left = new Tree('3');
root -> right = new Tree('3');
root -> left -> left = new Tree('4');
root -> left -> right = new Tree('6');
root -> right -> left = new Tree('6');
root -> right -> right = new Tree('4');
if (mirrorBt(root, root)){
cout<<"The given binary tree is showing the mirror image of the subtrees."<<endl;
}
else{
cout<<"It's not showing as the mirror image of the subtree."<<endl;
}
return 0;
}
Comments
Leave a comment