Swap every node's left and right children

Trees Junior Python 3.13+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
left, right = "L", "R"
left, right = right, left
print(left, right)

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A R L

Right: the right side is evaluated first, then unpacked.

The same tuple swap exchanges node.left and node.right in one line without a temporary.

Why not the others?
  • B L R. The tuple assignment does swap the two names.
  • C R R. Python builds the tuple (right, left) before assigning, so nothing is overwritten early.

30-second answer

Visit every node once and swap its children; the order of visits does not matter as long as each node is swapped exactly once. Recursively: swap, then recurse into both children. O(n) time, O(h) stack.

Practise saying it · 30 s. No recording, just a timer

Explain mirroring a tree in place.

Say your answer out loud, then check which of these points you covered:

  • Swap children at every node
  • Any visit order
  • O(n)

Deep dive

Python's tuple assignment node.left, node.right = node.right, node.left swaps safely.

A BFS or explicit-stack version avoids recursion depth limits.

Returning the root makes the function easy to chain and test.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def swap_sides(root: Node | None) -> Node | None:
    if root is not None:
        root.left, root.right = root.right, root.left
        swap_sides(root.left)
        swap_sides(root.right)
    return root

Common mistakes

  • Swapping, then recursing into the 'left' child twice because the reference changed.
  • Creating a new tree when the question asked for in place (or the reverse); ask.

Senior take & follow-ups

Mention in place vs new tree, then write the in-place version.

Follow-up questions

Think of your answer first, then open the hint.

  1. How would you do it without changing the input?

    Show hint

    Build new nodes: Node(val, mirror(right), mirror(left)).

  2. What is the space cost of the BFS version?

    Show hint

    O(w) for the widest row.

What each operation costs: Binary Tree · Binary Search Tree · Tree Traversal

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.