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 an array 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 an array of the values of all the nodes that are K distance from the target node.

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