EASY NC#46 Blind #62 Trees
226. Invert Binary Tree
๐ Problem
Given the root of a binary tree, invert the tree, and return its root.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขIn-place array updates
- โขSorted array traversal
- โขBoundary condition checks
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Two Pointers reasoning pattern
- โขApply BFS reasoning pattern
- โขApply Recursion reasoning pattern
๐ก Approach
- โ Swap left and right children recursively
- โ Base case: null node returns null
- โ Post-order traversal (process children before current node)
- โ Time: O(n), Space: O(h) where h is tree height
๐ ๏ธ Hints & Pitfalls
Hints
- โขSwap left and right children recursively
- โขBase case: null node returns null
- โขPost-order traversal (process children before current node)
Common Pitfalls
- โขTime: O(n), Space: O(h) where h is tree height
๐งช Test Cases
Hidden tests on submit: 3
Test Case 1
Not run Input:
invertTree(buildTree([4,2,7,1,3,6,9])); Expected:
{"val":4,"left":{"val":7,"left":{"val":9,"left":null,"right":null},"right":{"val":6,"left":null,"right":null}},"right":{"val":2,"left":{"val":3,"left":null,"right":null},"right":{"val":1,"left":null,"right":null}}} Test Case 2
Not run Input:
invertTree(buildTree([2,1,3])); Expected:
{"val":2,"left":{"val":3,"left":null,"right":null},"right":{"val":1,"left":null,"right":null}} Test Case 3
Not run Input:
invertTree(buildTree([])); Expected:
null ๐ Code Editor
๐ค Output