Binary Tree Mirror - Problem

Given the root of a binary tree, create its mirror image by swapping the left and right children of every node in the tree.

In a mirror image, every node's left subtree becomes its right subtree and vice versa. This transformation should be applied recursively to all nodes in the tree.

The function should modify the tree in-place and return the root of the mirrored tree.

Input & Output

Example 1 — Basic Binary Tree
$ Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
💡 Note: Mirror the tree by swapping left/right children at every node. Root 4's children swap from [2,7] to [7,2], node 2's children swap from [1,3] to [3,1], node 7's children swap from [6,9] to [9,6].
Example 2 — Single Node Tree
$ Input: root = [1]
Output: [1]
💡 Note: A single node has no children to swap, so the tree remains unchanged.
Example 3 — Empty Tree
$ Input: root = []
Output: []
💡 Note: An empty tree (null root) remains empty after mirroring.

Constraints

  • The number of nodes in the tree is in the range [0, 100]
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
INPUT TREEMIRROR ALGORITHMMIRRORED RESULT4271369Original: [4,2,7,1,3,6,9]1Start at root (4)2Swap children: 2↔73Recurse on node 74Swap children: 6↔95Recurse on node 26Swap children: 1↔3Each node: swap left↔right, then recurse4729631Mirrored: [4,7,2,9,6,3,1]Key Insight:Mirror a tree by swapping left and right children at every node - this can be doneefficiently in-place using recursion without creating any new nodes.TutorialsPoint - Binary Tree Mirror | In-Place DFS Mirror
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
77.7K Views
Medium Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen