Invert Binary Tree
Master this topic with zero to advance depth.
Invert Binary Tree
Given the root of a binary tree, invert the tree, and return its root.
Examples
Level I: Recursive DFS
Intuition
To invert a binary tree, we swap the left and right children of every node. This can be done recursively: swap children of the current node, then recurse into both subtrees.
Detailed Dry Run
root = [4,2,7] -> Swap(2,7) -> [4,7,2]. Recurse into subtrees.
Level II: Iterative BFS (Queue)
Intuition
Process the tree level by level. Use a queue to store nodes. For each node, swap its children and add them to the queue if they exist.
Detailed Dry Run
Queue: [4]. Pop 4, swap(2,7), Queue: [7,2]. Pop 7, swap(6,9)...
Level III: Iterative DFS (Stack)
Intuition
Similar to BFS, but use a stack. The order of traversal doesn't change the fact that every node's children need to be swapped.
Diagram
(1) Swap children of Root (2) Result after subtrees
4 4
/ \ / \
2 7 7 2
/ \ / \ / \ / \
1 3 6 9 9 6 3 1Detailed Dry Run
Stack: [4]. Pop 4, swap(2,7), Push(2,7). Pop 7, swap(6,9)... mirrored tree.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.