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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit