Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Mirror a binary tree (swap every node's children) and print its inorder traversal. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.

Problem: Mirror a binary tree (swap every node's children) and print its inorder traversal. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
from collections import deque
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):  # level order, None = missing child
    root = T(xs[0]); q = deque([root]); i = 1
    while i < len(xs):
        node = q.popleft()
        for side in ("l", "r"):
            if i < len(xs) and xs[i] is not None:
                setattr(node, side, T(xs[i])); q.append(getattr(node, side))
            i += 1
    return root
def invert(t):
    if t: t.l, t.r = invert(t.r), invert(t.l)
    return t
def inorder(t):
    return inorder(t.l) + [t.v] + inorder(t.r) if t else []
print(inorder(invert(build([5, 3, 8, 1, 4, None, 9]))))
What is printed?
  1. A. [5, 8, 3, 9, 4, 1]
  2. B. [9, 8, 5, 4, 3, 1]
  3. C. [1, 3, 4, 5, 8, 9]
  4. D. [9, 8, 5, 3, 4, 1]

Correct answer: B. [9, 8, 5, 4, 3, 1]

The original tree is a BST with inorder 1, 3, 4, 5, 8, 9. Mirroring swaps left and right everywhere, so the inorder of the mirror is exactly the original inorder reversed: 9, 8, 5, 4, 3, 1. The tuple assignment evaluates both recursive calls before assigning, so no subtree is lost. O(n).

More Coding Interview Problems questions

Exams that ask this topic