32 / 75
E

Invert Binary Tree

#32
treedfsbfs+1

Recursively swap left and right children of every node.

Example:

Input:root=[4,2,7,1,3,6,9]
Output:[4,7,2,9,6,3,1]

Common Mistakes:

  • Swapping before recursion (order matters - can cause issues)
  • Not storing temp reference before swapping
  • Trying to do in-place without proper temp variable
  • Overcomplicating with iterative approach when recursion is cleaner

Notes:

Famous problem (Max Hoscheler rejected from Google for not solving). Time O(n), Space O(h) for recursion. Can also solve iteratively with BFS queue.

32/75
Invert Binary Tree