Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
All Nodes Distance K in Binary Tree
Bookmark
Graph + BFS
Parent Map + BFS
Single DFS
Input
Example 1
Small
Single node
Complete tree
Custom
tree
=
[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]
,
target
=
5
,
k
=
2
dist
0
/ k
2
3
5
target
1
6
2
0
8
7
4
dist
0
/ k
2
3
5
target
1
6
2
0
8
7
4
dist
0
/ k
2
3
5
target
1
6
2
0
8
7
4
edge recorded both ways
dist
0
/ k
2
3
5
target
1
6
2
0
8
7
4
edge recorded both ways
dist
0
/ k
2
3
5
d0
target
1
6
2
0
8
7
4
5
front / rear
queue
queue = [5]
ring at distance 0
dist
0
/ k
2
3
d1
5
d0
target
1
6
2
0
8
7
4
3
front / rear
queue
enqueue
3
distance 1
dist
1
/ k
2
3
d1
5
d0
target
1
6
d1
2
d1
0
8
7
4
3
6
2
front
rear
queue
dist = 1
keep expanding
dist
1
/ k
2
3
d1
5
target
1
6
d1
2
d1
0
8
7
4
6
2
front
rear
queue
5 already visited
(shorter route exists)
dist
1
/ k
2
3
d1
5
d0
target
1
d2
6
d1
2
d1
0
8
7
4
2
1
front / rear
queue
dequeue
2
dist
1
/ k
2
3
d1
5
d0
target
1
d2
6
d1
2
d1
0
8
7
d2
4
d2
1
7
4
front
rear
queue
enqueue
4
distance 2
dist
2
/ k
2
3
d1
5
d0
target
1
d2
6
d1
2
d1
0
8
7
d2
4
d2
1
7
4
front
rear
queue
return [7, 4, 1]
7
4
1
algo
master
.
io
Step:
Find every node at distance 2 from the target node 5
0 / 29
Input
Example 1
Small
Single node
Complete tree
Custom
tree
=
[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]
,
target
=
5
,
k
=
2
0 / 29
algo
master
.
io
Step:
Find every node at distance 2 from the target node 5