Given the root of a binary tree, invert the tree by swapping all left and right children at every node, then return the modified root.

Inverting a binary tree means creating a mirror image of the original tree. Every left child becomes a right child, and every right child becomes a left child, recursively throughout the entire tree structure.

Goal: Transform the binary tree into its horizontal mirror reflection.
Input: The root node of a binary tree (or null for empty tree)
Output: The root node of the inverted binary tree

For example, if you have a tree where node 2 is the left child of root 4, after inversion, node 2 becomes the right child of root 4.

Input & Output

example_1.py โ€” Standard Binary Tree
$ Input: root = [4,2,7,1,3,6,9]
โ€บ Output: [4,7,2,9,6,3,1]
๐Ÿ’ก Note: The tree is inverted horizontally. Node 2 (originally left child of 4) becomes right child, and node 7 (originally right child) becomes left child. This pattern continues recursively for all subtrees.
example_2.py โ€” Simple Two-Node Tree
$ Input: root = [2,1,3]
โ€บ Output: [2,3,1]
๐Ÿ’ก Note: Left child 1 and right child 3 are swapped. The root remains at position 2 but its children are inverted.
example_3.py โ€” Empty Tree Edge Case
$ Input: root = []
โ€บ Output: []
๐Ÿ’ก Note: An empty tree remains empty after inversion. This is our base case - there are no nodes to swap.

Constraints

  • The number of nodes in the tree is in the range [0, 100]
  • Node values are in the range [-100, 100]
  • Follow-up: This problem was inspired by Max Howell's tweet about being rejected by Google despite inverting binary trees daily

Visualization

Tap to expand
Binary Tree Inversion ProcessOriginal Tree4271369Inverted Tree4729631INVERTStep-by-Step Process1. Recurse Left: Invert subtree rooted at node 22. Recurse Right: Invert subtree rooted at node 73. Swap Children: Make inverted-right the new left, inverted-left the new right4. Return Root: Return the root of the now-inverted tree
Understanding the Visualization
1
Identify Original Structure
Start with the original binary tree with nodes in their initial left-right positions
2
Apply Recursive Logic
At each node, recursively invert left and right subtrees
3
Swap Children
Swap the inverted left and right subtrees at current node
4
Return Inverted Tree
The result is a horizontally mirrored version of the original tree
Key Takeaway
๐ŸŽฏ Key Insight: Tree inversion is elegantly solved through recursion - invert subtrees first, then swap them at each level!
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
89.5K Views
High Frequency
~12 min Avg. Time
2.8K 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