Invert Binary Tree
Invert Binary Tree
Section titled “Invert Binary Tree”
Easy
Day 13 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Invert a binary tree by swapping the left and right children of every node.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
root = [4,2,7,1,3,6,9] - Output:
[4,7,2,9,6,3,1]
Example 2:
- Input:
root = [2,1,3] - Output:
[2,3,1]
Constraints:
0 ≤ tree nodes ≤ 100
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Tests recursive tree transformation. Made famous by a Google interview story.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Pattern: Tree Transformation
Solve for children first (post-order), then transform the current node.
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD Root["TreeNode (Root)"] -->|Recurse Left| Left["Left Subtree"] Root -->|Recurse Right| Right["Right Subtree"] Left --> Base1{"Base Case (null)"} Right --> Base2{"Base Case (null)"} Base1 --> Combine["Combine Results"] Base2 --> Combine Combine --> Ans["Return Root Value / Depth"]🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”// Recursive is standard- Time Complexity:
O(n) - Space Complexity:
O(h) - Explanation: Recursive post-order swap.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function invertTree(root) { if (!root) return null; const temp = root.left; root.left = invertTree(root.right); root.right = invertTree(temp); return root;}- Time Complexity:
O(n) - Space Complexity:
O(h) - Explanation: Recursive post-order inversion.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”- Go down to leaves first (post-order)
- Swap at each level as you return
- Tree remains valid — just mirrored
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Swap left and right children.
- Recursively invert subtrees before swapping.
- Base case: null returns null.