Skip to content
mlmentorship

Return transformed child roots, then reconnect them locally

Mirror every subtree while preserving node identities, then change execution or return a separate copy.

Published · 8 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Return transformed child roots, then reconnect them locally

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. The root of an owned finite binary tree, with val, left, and right fields on each node. Output. Return the original root object after mirroring the complete tree. Rules. Exchange left and right children at every node, not only at the root. Reuse existing nodes and retain their values; do not create a separate copied tree. Assume no cycles or shared nodes. An empty tree returns None. Example. A root 4 with children 2 and 7 becomes a root 4 with children 7 and 2. The full level-order tree [4, 2, 7, 1, 3, 6, 9] becomes [4, 7, 2, 9, 6, 3, 1].

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Postorder recursion returns inverted child subtrees, then the parent assigns old right to left and old left to right.

Problem trace

Swap returned subtrees, not the values stored in their nodes

Worked example: swap subtree positions without changing their stored valuesEach node swaps its child links. Root one keeps its value, while nodes two and four move together. Descendant links also mirror; this is not merely a value swap.Mirror child links, not merely storedvaluesBefore: 2 and 4 in the left subtree12435Node values unchanged.After: 2 and 4 in the right subtree13524Node values unchanged.
Read it this way: Each node swaps its child links. Root one keeps its value, while nodes two and four move together. Descendant links also mirror; this is not merely a value swap. Would swapping only stored values two and three move their descendants to the correct mirrored positions?
Full interview answer 8 min read

Mirror an entire binary tree in place while retaining the identities of its existing nodes.

Problem

Input. The root of an owned finite binary tree, with val, left, and right fields on each node.

Output. Return the original root object after mirroring the complete tree.

Rules. Exchange left and right children at every node, not only at the root. Reuse existing nodes and retain their values; do not create a separate copied tree. Assume no cycles or shared nodes. An empty tree returns None.

Example. A root 4 with children 2 and 7 becomes a root 4 with children 7 and 2. The full level-order tree [4, 2, 7, 1, 3, 6, 9] becomes [4, 7, 2, 9, 6, 3, 1].

Picture

Turn each branch into its mirror before attaching it to the opposite side. Old right subtree 7 becomes 7(9,6). Old left subtree 2 becomes 2(3,1). Root 4 then connects left to 7 and right to 2.

Problem trace

Swap returned subtrees, not the values stored in their nodes

Input and goalSwap the left and right children at every node.
Start with the original linksFor tree [4,2,7,1,3,6,9], call invert_tree(4). The root currently links left to 2 and right to 7.
callStack[4]links4.left=2; 4.right=7
node 4
call invert(4)
call stack
[4]
links
4.left=2; 4.right=7

Recognize it
Use this pattern when every node applies the same local child-pointer transformation and the parent needs transformed child roots returned from recursion.
Keep true
invert_tree(node) returns the same node object after every edge in its subtree is mirrored: its new left is the fully inverted old right and its new right is the fully inverted old left.
Reuse it
For recursive structural edits, first obtain transformed child roots, then reconnect them locally and return the current root; this transfers to pruning, flattening, and persistent tree rewrites.
For tree [4,2,7,1,3,6,9], call invert_tree(4). The root currently links left to 2 and right to 7. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: At the root, which returned subtree becomes the new left child, and did any node value change?
Reference drawing

Problem trace

Swap returned subtrees, not the values stored in their nodes

Worked example: swap subtree positions without changing their stored valuesEach node swaps its child links. Root one keeps its value, while nodes two and four move together. Descendant links also mirror; this is not merely a value swap.Mirror child links, not merely storedvaluesBefore: 2 and 4 in the left subtree12435Node values unchanged.After: 2 and 4 in the right subtree13524Node values unchanged.
Execution trace
Input and goalSwap the left and right children at every node.
Start with the original linksFor tree [4,2,7,1,3,6,9], call invert_tree(4). The root currently links left to 2 and right to 7.
callStack[4]links4.left=2; 4.right=7
node 4
call invert(4)
call stack
[4]
links
4.left=2; 4.right=7

Recognize it
Use this pattern when every node applies the same local child-pointer transformation and the parent needs transformed child roots returned from recursion.
Keep true
invert_tree(node) returns the same node object after every edge in its subtree is mirrored: its new left is the fully inverted old right and its new right is the fully inverted old left.
Reuse it
For recursive structural edits, first obtain transformed child roots, then reconnect them locally and return the current root; this transfers to pruning, flattening, and persistent tree rewrites.
For tree [4,2,7,1,3,6,9], call invert_tree(4). The root currently links left to 2 and right to 7. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: At the root, which returned subtree becomes the new left child, and did any node value change?
Read it this way: Each node swaps its child links. Root one keeps its value, while nodes two and four move together. Descendant links also mirror; this is not merely a value swap. Would swapping only stored values two and three move their descendants to the correct mirrored positions?

The recursive return contract is: this same node now roots the complete mirror of its former subtree. Values and node identities remain unchanged; child links change.

Code

def invert_tree(root: TreeNode | None) -> TreeNode | None:
   if root is None:
      return None
   root.left, root.right = invert_tree(root.right), invert_tree(root.left)
   return root

Python evaluates the old right recursion first, then the old left recursion. Both results are ready before either assignment target changes. This preserves both old child references during evaluation.

Each node is visited once: time and recursive stack space. Height can equal ; Python’s recursion limit still applies.

Failure Check

Swapping only root children produces [4,7,2,6,9,1,3], not the full mirror. Assigning root.left = root.right before preserving old left loses access to subtree 2 through this root.

Change the Execution

New task: Keep in-place mutation without recursive calls.

Picture and change: Pop one node, swap its links, then schedule its real children. Traversal order changes; the final mirror and node identities do not.

def invert_iterative(root):
   stack = [] if root is None else [root]
   while stack:
      node = stack.pop()
      node.left, node.right = node.right, node.left
      if node.left is not None:
         stack.append(node.left)
      if node.right is not None:
         stack.append(node.right)
   return root

Check: The source tree reaches the same mirror. Inverting twice restores every original link and value. Time is , with auxiliary space on a binary tree.

Use when: Mutation is permitted but recursive depth is unsuitable.

Change the Ownership

New task: Leave the original tree unchanged.

Picture and change: Allocate one new node for each old node. Assume the compatible constructor TreeNode(val, left=None, right=None).

def inverted_copy(root):
   if root is None:
      return None
   return TreeNode(root.val, inverted_copy(root.right), inverted_copy(root.left))

Check: Require mirrored values and links, unchanged original links, and disjoint original/copy node identities. This takes time, new-node storage, and recursive stack space. It is not in-place or safe for arbitrary cyclic graphs.

Use when: Ownership forbids changing the input.

Transfer Check

Why can the original assignment safely use both old child links?

Answer

Both right-hand expressions finish before either left-hand target is assigned. That ordering prevents overwriting the old left reference before its recursive call. For shared or cyclic structures, establish an aliasing policy instead; compare graph cloning.