Skip to the solution
EasyDSA12 min read

How do you invert a binary tree?

533 views

The problem

Question presented to candidate: "Given the root of a binary tree, invert it โ€” mirror it so every node's left and right children are swapped โ€” and return the root. Please write it in Python, then show me a version that would not hit the recursion limit."

What a strong answer should cover:

  • Inverting means swapping the left and right child at every node, not just the root; any traversal order works because each node is swapped once.
  • A recursive version (swap, then recurse, or recurse, then swap) and an iterative BFS with collections.deque.
  • O(n) time; O(h) space recursively, O(w) for BFS; in place, no new nodes.
  • The assignment-order bug: two separate assignments with recursive calls overwrite node.left before it is read.
  • Python specifics: the tuple swap node.left, node.right = invert(node.right), invert(node.left) evaluates the whole right-hand side first, so it is safe; the default recursion limit of 1000 makes BFS the safe choice for deep trees.

Clarifying questions expected:

  • "Should I invert in place or return a new tree?"
  • "How deep can the tree be?"

Code / implementation expected: Yes โ€” a short recursive Python function, ideally with an iterative BFS version too.

  • dsa
  • binary-tree
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonRecursive invert on six trees, shown in level-order form
PythonIterative BFS invert, the two-step assignment bug, and a 100000-node chain

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 25 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How should you approach a DSA problem in a coding interview?

Continue