Q9: Invert Binary Tree

Invert or mirror a binary tree recursively by swapping left and right child pointers for every node in the tree.

Recursive Binary Tree Inversion
function invertTree(root) {
  if (root === null) return null;
  
  const temp = root.left;
  root.left = invertTree(root.right);
  root.right = invertTree(temp);
  
  return root;
}
💡 Base case returns null. At each node, its left child receives the inverted right subtree and its right child receives the inverted left subtree.
Key Takeaways
  • Uses Depth-First Search (DFS) tree recursion.
  • Swaps .left and .right pointers at every level.
Knowledge Check

What is the time complexity of inverting a binary tree with N nodes?