Skip to content
mlmentorship

Invert Binary Tree

Swap the left and right children at every node.

Published · 4 min read ·Core ·Intermediate

30-second answer map

Visual first · depth when needed

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

Preparing the visual…

ML breadth · active recall

Practice before you read

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

How practice works

ML breadth · closed-book attempt

Invert Binary Tree

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

08:00recommended time

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

Swap the left and right children at every node.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

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

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

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.
Read it this way: 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.

Pattern: Tree DFS.

Simple idea: Invert both child trees, then place the old right result on the left and the old left result on the right.

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

Cost: time and call-stack space.

The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.