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, K
.
Return a list of the values of all nodes that are K
distance from the target
node.
Input
The following is an example input:
3
/ \
5 1
| / \
2 15 7
/ \
7 4
target = 5
K = 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
.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.