all entries
A-046Day 462026.06.21easyleetcode #226neetcode150

Invert Binary Tree

#tree#depth-first-search#breadth-first-search#binary-tree
leetcode #226 · invert-binary-tree
01

Problem

· problem
P.046

Invert Binary Tree

leetcode #226

Given 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
example 1input → output
[4,2,7,1,3,6,9]
[4,7,2,9,6,3,1]
example 2input → output
[2,1,3]
[2,3,1]
example 3input → output
[]
[]
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 rightnested
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 subtreenested
self.invertTree(root.left)
self.invertTree(root.right)
self.invertTree(root.left.left)
step 4· Recursion: Process right subtreenested
self.invertTree(root.right)
self.invertTree(root.left)
pass
step 5· Return: Return the inverted nodenested
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

· solve
solution.py
1
# Definition for a binary tree node.
2
# class TreeNode:
3
#     def __init__(self, val=0, left=None, right=None):
4
#         self.val = val
5
#         self.left = left
6
#         self.right = right
7
class Solution:
8
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
9
        if not root:
10
            return None
11
        
12
        # swap the children
13
        root.left, root.right = root.right, root.left
14
        
15
        # make 2 recursive calls
16
        self.invertTree(root.left)
17
        self.invertTree(root.right)
18
        return root
mental 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.