Answer to Question #272297 in C for William

Question #272297

Write a program to check that the left sub-tree of an binary tree (Not BST) is mirror image of its right sub-tree.


1
Expert's answer
2021-11-27T11:38:11-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS