Skip to main content

77. Invert Binary Tree

easyAsked at Reddit

Invert a binary tree (mirror left and right at every node). Reddit asks this canonical question — connects to alternating-view rendering in their right-side-vs-left-side AB tests.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Source citations

Public interview reports confirming this problem appears in Reddit loops.

  • Glassdoor (2026-Q1)Reddit phone screen, easy warm-up.

Problem

Given the root of a binary tree, invert the tree, and return its root.

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Examples

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]

Approaches

1. Recursive

Swap left and right; recurse on each.

Time
O(n)
Space
O(h)
function invertTree(root) {
  if (!root) return null;
  [root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
  return root;
}

Tradeoff: One-liner. O(h) recursion stack.

2. Iterative BFS (optimal for deep trees)

Queue; swap children of each popped node.

Time
O(n)
Space
O(w)
function invertTree(root) {
  if (!root) return null;
  const q = [root];
  while (q.length) {
    const n = q.shift();
    [n.left, n.right] = [n.right, n.left];
    if (n.left) q.push(n.left);
    if (n.right) q.push(n.right);
  }
  return root;
}

Tradeoff: Iterative — handles deep trees without stack risk.

Reddit-specific tips

Reddit interviewers want either. Bonus signal: mention this is the meme-question (Max Howell + Google) and stay matter-of-fact about both versions.

Common mistakes

  • Returning root.left (must return root itself).
  • Mutating without recursing (only swaps root's children).
  • Stack-overflow on deep trees (use iterative).

Follow-up questions

An interviewer at Reddit may pivot to one of these next:

  • Symmetric tree (LC 101).
  • Flatten binary tree to linked list (LC 114).
  • Mirror a doubly linked list.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

FAQ

Is inversion commutative with order of operations?

Yes — swap children of every node, in any traversal order.

Does the value change?

No, only the .left/.right references.

Practice these live with InterviewChamp.AI

Drill Invert Binary Tree and other Reddit interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →