- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create a mirror tree from the given binary tree in C++ Program
In this tutorial, we are going to reflect the given binary tree.
Let's see the steps to solve the problem.
Write a struct node.
Create the binary tree with dummy data.
Write a recursive function to find the mirror of the given binary tree.
Recursively call the function with left and right nodes.
Swap the left node data with the right node data.
Print the tree.
Example
Let's see the code.
#include<bits/stdc++.h> using namespace std; struct Node { int data; struct Node* left; struct Node* right; }; struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = NULL; node->right = NULL; return node; } void convertTreeToItsMirror(struct Node* node) { if (node == NULL) { return; } else { struct Node* temp; convertTreeToItsMirror(node->left); convertTreeToItsMirror(node->right); temp = node->left; node->left = node->right; node->right = temp; } } void printTree(struct Node* node) { if (node == NULL) { return; } printTree(node->left); cout << node->data << " "; printTree(node->right); } int main() { struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Tree: "; printTree(root); cout << endl; convertTreeToItsMirror(root); cout << "Mirror of the Tree: "; printTree(root); cout << endl; return 0; }
Output
If you run the above code, then you will get the following result.
Tree: 4 2 5 1 3 Mirror of the Tree: 3 1 5 2 4
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements
To Continue Learning Please Login
Login with Google