---
Difficulty: Easy
Source: 160 Days of Problem Solving
Tags:
- Tree
---
# π _Day 4. Mirror Tree_ π§
The problem can be found at the following link: [Question Link](https://www.geeksforgeeks.org/batch/gfg-160-problems/track/tree-gfg-160/problem/mirror-tree)
## π‘ **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 Walkthrough:**
### **Example 1:**
#### **Input:**
```
1
/ \
2 3
/
4
```
#### **Output:**
```
1
/ \
3 2
\
4
```
#### **Explanation:**
Every non-leaf node has its left and right children interchanged.
### **Example 2:**
#### **Input:**
```
1
/ \
2 3
/ \
4 5
```
#### **Output:**
```
1
/ \
3 2
/ \
5 4
```
#### **Explanation:**
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)**
1. **Base Case:** If the node is `NULL`, return.
2. **Recursively traverse** the left and right subtrees.
3. **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)` OR `O(H)` for recursive DFS (`H = height of the tree`).
## π **Solution Code**
## Code (C)
```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 4
```
The output after compilation and running:
```
1 3 2
```
Expected output:
```
1 3 2 N 4
```
Although there is a difference in output format during execution, submitting the code results in a **successful pass for all test cases**.
## Code (C++)
```cpp
class Solution {
public:
void mirror(Node* node) {
if (!node) return;
mirror(node->left);
mirror(node->right);
swap(node->left, node->right);
}
};
```
### **2οΈβ£ Iterative BFS (Level Order)**
```cpp
class Solution {
public:
void mirror(Node* root) {
if (!root) return;
queueπ² Alternative Approaches