DIY: All Nodes Distance K in Binary Tree
Solve the interview question "All Nodes Distance K in Binary Tree" in this lesson.
We'll cover the following
Problem statement
We are given a binary tree (with a root node root
), a target
node, and an integer value, kk
.
Return a list of the values of all nodes that are kk
distance from the target
node.
Input
The following is an example input:
3
/ \
5 1
| / \
2 15 7
/ \
7 4
target = 5
kk = 2
Output
The following is an example output:
[7,4,1]
The nodes that are a distance 2
from the target node 5
have the values 7
, 4
, and 1
.
Coding exercise
For this coding exercise, you need to implement the distance_k(root, target, kk)
function, where root
is the root node of the binary tree and target
is where we start calculating the distance kk
. The function will return a list of the values of all the nodes that are kk
distance from the target
node.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.