इस ट्यूटोरियल में, हम एक प्रोग्राम पर चर्चा करेंगे जो बाइनरी ट्री को उसके मिरर ट्री में परिवर्तित करता है।
इसके लिए हमें एक बाइनरी ट्री प्रदान की जाएगी। हमारा कार्य लेफ्ट और राइट एंड पर मानों को स्वैप करके दिए गए बाइनरी ट्री से एक मिरर ट्री बनाना होगा।
उदाहरण
#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 = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
void mirror(struct Node* node) {
if (node == NULL)
return;
else {
struct Node* temp;
// सबट्रीज़ को स्वैप करना
mirror(node->left);
mirror(node->right);
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
// इनऑर्डर ट्रैवर्सल प्रिंट करना
void print_tree(struct Node* node) {
if (node == NULL)
return;
print_tree(node->left);
cout << node->data << " ";
print_tree(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 << "Inorder traversal of the constructed" << endl;
print_tree(root);
mirror(root);
// मिरर ट्री प्रिंट करना
cout << "\nInorder traversal of the mirror tree" << endl;
print_tree(root);
return 0;
}
आउटपुट
Inorder traversal of the constructed 4 2 5 1 3 Inorder traversal of the mirror tree 3 1 5 2 4