Question presented to candidate: "Given the root of a binary tree, write a Python function that returns True if the tree is a mirror of itself โ symmetric around its centre โ and False otherwise. Can you do it both recursively and iteratively?"
What a strong answer should cover:
- Reduce the problem to a two-argument mirror check:
is_mirror(root.left, root.right). - The four cases: both None, exactly one None, different values, then outer pair and inner pair.
- An iterative version with a
dequeof node pairs (pairs containingNoneare fine). - O(n) time, O(h) recursion or O(w) queue space; why an inorder palindrome check is wrong.
- Python specifics: compare values with
==, notis(istests object identity and fails for larger ints built at runtime);andshort-circuits; the recursion limit of 1000 limits the recursive version on deep trees.
Clarifying questions expected:
- "Must the shape mirror as well as the values?"
- "Should an empty tree count as symmetric?"
Code / implementation expected: Yes โ a recursive Python helper on two nodes, and ideally an iterative queue-of-pairs version.