Invert Binary Tree
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trees.
Invert Binary Tree
Given the
root of a binary tree, invert the tree, and return its root.Examples
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Approach 1
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.
⏱ O(N)💾 O(H)
Detailed Dry Run
root = [4,2,7] -> Swap(2,7) -> [4,7,2]. Recurse into subtrees.
Approach 2
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.
⏱ O(N)💾 O(W)
Detailed Dry Run
Queue: [4]. Pop 4, swap(2,7), Queue: [7,2]. Pop 7, swap(6,9)...
Approach 3
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 1⏱ O(N)💾 O(H)
Detailed Dry Run
Stack: [4]. Pop 4, swap(2,7), Push(2,7). Pop 7, swap(6,9)... mirrored tree.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.