Challenge: Find Nodes at "k" Distance from the Root
Given the root to a Binary Search Tree and a value "k", write a function to find the nodes at "k" distance from the root. A solution is placed in the "solution" section to help you, but we would suggest you try to solve it on your own first.
We'll cover the following
Problem Statement
In this problem, you have to implement the findKNodes() function to find nodes at k distance from the root in the given Binary Tree. An illustration is also provided for your understanding.
Function Prototype
String findKNodes(Node root, int k);
Here, root is the root node of the Binary Tree and k is an integer number.
Output
It returns all the nodes at k distance from the root node in a string format.
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
Explanation
The depth of a node is equal to the number of edges between that node and the root of tree. The depth of Nodes 2,5,8 and 12 is 2. Here’s an illustration of the given challenge:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.