Challenge: Find Nodes at "k" Distance From the Root

If you are given the root to a Binary Search Tree and a node value "k", can you write a code to find the nodes at "k" distance from the root? A solution is placed in the "solution" section for your help, but we would suggest you ​solve it on your own first.

Problem Statement

Implement a function findKNodes(root,k) that finds and returns nodes at k distance from the root in the given binary tree. An illustration is also provided for your understanding.

Input

The root node of a BST and any number k

Output

Returns all nodes in a list format which are at k distance from the root node.

Sample Input

bst = {
		6 -> 4,9
    4 -> 2,5
    9 -> 8,12
    12 -> 10,14
}
where parent -> leftChild,rightChild
k = 2

Sample Output

[2,5,8,12]

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