इस ट्यूटोरियल में, हम दिए गए बाइनरी ट्री को प्रतिबिंबित (mirror) करना सीखेंगे।
समस्या को हल करने के चरण देखते हैं।
एक स्ट्रक्चर नोड लिखें।
डमी डेटा के साथ बाइनरी ट्री बनाएं।
दिए गए बाइनरी ट्री का मिरर खोजने के लिए एक रिकर्सिव फंक्शन लिखें।
लेफ्ट और राइट नोड्स के साथ फंक्शन को रिकर्सिवली कॉल करें।
लेफ्ट नोड के डेटा को राइट नोड के डेटा से स्वैप करें।
ट्री को प्रिंट करें।
उदाहरण
कोड देखते हैं।
#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; }आउटपुट
यदि आप उपरोक्त कोड चलाते हैं, तो आपको निम्न परिणाम मिलेगा।
Tree: 4 2 5 1 3 Mirror of the Tree: 3 1 5 2 4
निष्कर्ष
यदि ट्यूटोरियल में आपके कोई प्रश्न हैं, तो उन्हें कमेंट सेक्शन में बताएं।