Algorithm-Day39-Invert-Binary-Tree-lc-226
🧩 Problem Description
Given the root
of a binary tree, invert the tree, and return its root.
Inverting a binary tree means swapping every left and right child recursively.
💬 Example
1 | Input: root = [4,2,7,1,3,6,9] |
💡 Approach: Recursive DFS
We recursively invert left and right subtrees, then swap them.
🔢 Java Code (Recursive)
1 | class Solution { |
💡 Approach: Iterative BFS (Queue)
You can also invert using level-order traversal with a queue.
🔢 Java Code (Iterative BFS)
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(n) — visit every node once
- Space Complexity:
- Recursive: O(h) (call stack)
- Iterative: O(w) (queue width)
✍️ Summary
- Simple yet classic recursion problem.
- Test your understanding of binary tree traversal.
- Also seen in real-world scenarios like image mirror effects.