A-046● Day 462026.06.21easyleetcode #226neetcode150
Invert Binary Tree
#tree#depth-first-search#breadth-first-search#binary-tree
01
Problem
· problemGiven the root of a binary tree, invert the tree, and return its root. Inverting a tree means swapping the left and right children at every node.
constraints
- · The number of nodes in the tree is in the range [0, 100]
- · -100 ≤ Node.val ≤ 100
// paraphrased summary — see source for full text
examples
02
Pre-solve
· pre-solve● 1list shown→● 2select→● 3reveal
- ☐What exactly does it mean to invert a tree?
- ☐Should we modify the original tree in-place or create a new tree?
- ☐Can we use iteration (BFS/queue) instead of recursion?
- ☐How should we handle an empty tree?
- ☐Should we also reverse the order of node values?
- ☐Do we only need to invert leaf nodes?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03
Logic Structure
· logic● 1slots shown→● 2pick per slot→● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Base Case: Check for null node
○
if not root:
○
if root is None:
○
if not root.left and not root.right:
step 2· Swap Children: Exchange left and right│ nested
○
root.left, root.right = root.right, root.left
○
temp = root.left root.left = root.right root.right = temp
○
root.left, root.right = root.left, root.right
step 3· Recursion: Process left subtree│ nested
○
self.invertTree(root.left)
○
self.invertTree(root.right)
○
self.invertTree(root.left.left)
step 4· Recursion: Process right subtree│ nested
○
self.invertTree(root.right)
○
self.invertTree(root.left)
○
pass
step 5· Return: Return the inverted node│ nested
○
return root
○
return None
○
return root.left
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04
Solve · Trace
· solvemental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[4,2,7,1,3,6,9]→
[4,7,2,9,6,3,1]
case 2
[2,1,3]→
[2,3,1]
case 3
[]→
[]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.