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.leftbefore 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.