Invert Binary Tree - Problem
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.
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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code