DIY: All Nodes Distance K in Binary Tree

Solve the interview question "All Nodes Distance K in Binary Tree" in this lesson.

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.

Coding exercise

For this coding exercise, you need to implement the distanceK(root, target, k) function, where root is the root node of the binary tree and target is where we start calculating the distance k. The function will return a list of the values of all the nodes that are k distance from the target node.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.