Understanding the Problem
We are given a binary tree and asked to return its mirror image.
Mirroring a binary tree means swapping the left and right subtrees of every node in the tree recursively.
The root stays the same, but its children, and all children below, are flipped horizontally.
This transformation turns a left-heavy tree into a right-heavy one and vice versa.
The challenge lies in performing this transformation correctly for all types of binary trees — including balanced trees, skewed trees, and edge cases like a single-node or empty tree.
Step-by-Step Solution with Example
Step 1: Define the Task Clearly
We want to traverse the binary tree and, for every node we visit, swap its left and right child.
This needs to be done for all nodes in the tree, which means recursion is a natural fit.
Step 2: Pick an Example
Let’s take a simple binary tree:
1
/ 2 3
Its mirror image would look like this:
1
/ 3 2
Step 3: Recursively Swap Children
Starting at the root node (1), we swap the left (2) and right (3) children.
Then, we go deeper and apply the same swapping logic recursively on node 2 and node 3.
If node 2 and 3 have children, their left and right children would also be swapped, and so on.
Step 4: Write the Recursive Logic
The recursive steps can be described as:
- If the current node is null, return null (base case)
- Swap its left and right child
- Recursively call the function on the left child
- Recursively call the function on the right child
Edge Cases
Case 1: Left-Skewed Tree
Example: [1, 2, null, 3]
becomes [1, null, 2, null, 3]
This demonstrates how the left-only structure becomes right-only after mirroring.
Case 2: Right-Skewed Tree
Example: [1, null, 2, null, 3]
becomes [1, 2, null, 3]
Right-only nodes become left-only, following the same recursive logic.
Case 3: Single Node Tree
Input: [1]
Output remains: [1]
Since there's no child to swap, the tree stays the same.
Case 4: Empty Tree
Input: []
→ Output: []
No nodes to process. Function should handle this safely and return null or equivalent.
Finally
This problem is a classic example of recursive tree traversal.
By understanding the structure of the binary tree and applying a simple left-right swap at every node,
we can generate its mirror efficiently.
It’s important to consider edge cases like null nodes, skewed trees, and minimal structures during implementation.
Always test your function with various types of trees to ensure robustness.
Comments
Loading comments...