Python coding

Mirror a binary tree

Write mirror(root): turn the binary tree into its mirror image, so that at every node the left and right children trade places, all the way down, and return the root of the result. You may change the tree in place or build a new one; an empty tree stays empty. Each TreeNode has val, left and right.

The tests call the provided run_mirror(values), where values lists the tree level by level with null for a missing child: [1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3. Your result comes back in the same format.

  • run_mirror([4,2,7,1,3,6,9]) → [4,7,2,9,6,3,1]
  • run_mirror([1,2]) → [1,null,2]
  • run_mirror([]) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The mirror of a tree is its root with the mirror of the right subtree on the left and the mirror of the left subtree on the right. An empty tree is its own mirror.

Hint 2

Compute both mirrored subtrees before you assign either: root.left = mirror(root.right) followed by root.right = mirror(root.left) reads the child you just replaced.

Solution and why it works
pythonO(n) · O(h), h = height (recursion stack)
# --- your code ---
def mirror(root: "TreeNode | None") -> "TreeNode | None":
    if root is not None:
        # one tuple assignment: both subtrees are mirrored before either link changes
        root.left, root.right = mirror(root.right), mirror(root.left)
    return root


# --- provided: do not edit ---
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build_tree(values: list[int | None]) -> TreeNode | None:
    # Level order: each existing node takes the next two entries as its left and right child.
    nodes = [None if v is None else TreeNode(v) for v in values]
    children = iter(nodes[1:])
    for node in nodes:
        if node is not None:
            node.left = next(children, None)
            node.right = next(children, None)
    return nodes[0] if nodes else None


def to_values(root: TreeNode | None, limit: int) -> list[int | None]:
    # The inverse of build_tree: level order, None for a missing child, no trailing None.
    out, queue, count = [], [root], 0
    for node in queue:                    # the list grows while we walk it: a BFS queue
        if node is None:
            out.append(None)
            continue
        count += 1
        if count > limit:
            raise ValueError("the result has more nodes than the input: is a node linked twice?")
        out.append(node.val)
        queue += [node.left, node.right]
    while out and out[-1] is None:
        out.pop()
    return out


def run_mirror(values: list[int | None]) -> list[int | None]:
    return to_values(mirror(build_tree(values)), sum(v is not None for v in values))

Every subtree needs the same fix as the whole tree: mirror its two subtrees and swap them. One recursion visits each node once, O(n) time, with a stack as deep as the tree, O(h). The trap is the order of the assignments: root.left = mirror(root.right) and then root.right = mirror(root.left) reads the left child you just overwrote, so both links end up pointing at the same subtree. Swap with one tuple assignment, or keep both results first. A BFS that swaps the children of each node also works.