बाइनरी सर्च ट्री को इनवर्ट करने के लिए, हम InvertABinarySearchTree मेथड को कॉल करते हैं जो नोड को पैरामीटर के रूप में लेता है। यदि नोड null है तो null लौटाएं, यदि नोड null नहीं है, तो हम लेफ्ट और राइट चाइल्ड मान पास करके InvertABinarySearchTree को रिकर्सिवली कॉल करते हैं। और राइट चाइल्ड मान को लेफ्ट चाइल्ड और लेफ्ट चाइल्ड मान को राइट चाइल्ड पर असाइन करते हैं। अंतिम आउटपुट में वह ट्री होगा जो अपनी खुद की मिरर इमेज होगी।
उदाहरण
public class TreesPgm{ public class Node{ public int Value; public Node LeftChild; public Node RightChild; public Node(int value){ this.Value = value; } public override String ToString(){ return "Node=" + Value; } } public Node InvertABinarySearchTree(Node node){ if (node == null){ return null; } Node left = InvertABinarySearchTree(node.LeftChild); Node right = InvertABinarySearchTree(node.RightChild); node.LeftChild = right; node.RightChild = left; return root; } }
इनपुट
1 3 2
आउटपुट
1 2 3