Challenge 5: Finding 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?

Problem statement

Implement a function string findKNodes(Node* root, int k) , which finds and returns nodes at k distance from the root in the given binary tree.

Input

This is the root node and a number k.

Output

It returns all nodes in a stringed 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 80+ hands-on prep courses.