5. Mirror Tree
The problem can be found at the following link: Question Link
Problem Description
Given a binary tree, convert it into its Mirror Tree by swapping the left and right children of all non-leaf nodes.
Example 1:
Input:
1
/ \
2 3
/
4Output:
1
/ \
3 2
\
4Explanation:
Every non-leaf node has its left and right children interchanged.
Example 2:
Input:
1
/ \
2 3
/ \
4 5Output:
1
/ \
3 2
/ \
5 4Explanation:
Every non-leaf node has its left and right children interchanged.
Constraints:
1 ≤ number of nodes ≤ $10^5$
1 ≤ node->data ≤ $10^5$
My Approach
Recursive DFS (Top-Down)
Base Case: If the node is
NULL, return.Recursively traverse the left and right subtrees.
Swap the left and right children of the current node.
Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N), since every node is visited once.Expected Auxiliary Space Complexity:
O(1)ORO(H)for recursive DFS (H = height of the tree).
Code (C)
void mirror(Node *n) {
if (!n) return;
mirror(n->left);
mirror(n->right);
Node* t = n->left;
n->left = n->right;
n->right = t;
}Note: The C code may show an error when compiled and run, but if you proceed with submission, it still passes all test cases.
For example, consider the input:
1 2 3 N N 4The output after compilation and running:
1 3 2Expected output:
1 3 2 N 4Although there is a difference in output format during execution, submitting the code results in a successful pass for all test cases.
Code (C++)
class Solution {
public:
void mirror(Node* node) {
if (!node) return;
mirror(node->left);
mirror(node->right);
swap(node->left, node->right);
}
};Code (Java)
class Solution {
void mirror(Node node) {
if (node == null) return;
mirror(node.left);
mirror(node.right);
Node temp = node.left;
node.left = node.right;
node.right = temp;
}
}Code (Python)
class Solution:
def mirror(self, root):
if not root:
return
self.mirror(root.left)
self.mirror(root.right)
root.left, root.right = root.right, root.leftContribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated