Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Invert Binary Tree
Bookmark
Recursive DFS
BFS Level-Order
Iterative Stack
Input
Example 1
Simple Tree
Left Child Only
Custom
tree
=
[4, 2, 7, 1, 3, 6, 9]
4
2
7
1
3
6
9
call stack
invert: invert both subtrees, then swap them
4
2
7
1
3
6
9
call stack
invert: invert both subtrees, then swap them
4
2
7
1
3
6
9
node
call stack
4
2
1
top
invert(
1
)
4
2
7
1
3
6
9
node
call stack
4
2
3
top
invert(
3
)
4
2
7
1
3
6
9
node
call stack
4
2
top
subtree inverted → return, pop the call stack
4
2
7
1
3
6
9
node
call stack
4
top
subtree inverted → return, pop the call stack
4
2
7
1
3
6
9
node
call stack
4
7
6
top
leaf
6
: nothing to swap
4
2
7
1
3
6
9
node
call stack
4
7
9
top
leaf
9
: nothing to swap
4
2
7
1
3
6
9
node
call stack
4
7
top
swap
6
↔
9
4
2
7
1
3
6
9
node
call stack
4
top
swap
2
↔
7
4
2
7
1
3
6
9
call stack
tree inverted, return root
algo
master
.
io
Step:
Start: invert both subtrees of every node, then swap them (post-order)
0 / 25
Input
Example 1
Simple Tree
Left Child Only
Custom
tree
=
[4, 2, 7, 1, 3, 6, 9]
0 / 25
algo
master
.
io
Step:
Start: invert both subtrees of every node, then swap them (post-order)