Given a binary tree, a target node in the binary tree, and an integer value k, find all the nodes that are at distance k from the given target node. No parent pointers are available.
First line of input contains the number of test cases T. For each test case, there will be three lines of input first of which is a string representing the tree as described below:
The values in the string are in the order of level order traversal of the tree where, numbers denotes node values, and a character “N” denotes NULL child.
Second line of test case holds the integer value target.
Third line hold the value k.
All the space separated nodes that are at distance k from the given target node in sorted order.
Your task is to complete the function KDistanceNodes(). This function returns the sorted list of nodes at k distance from target. Returned list will be printed by driver code.
1 <= T <= 200
1 <= no of edges <= 1000
1<= data of node <= 10000
1 <= target <= 10000
1 <= k <= 20
Expected time complexity: O(N)
Expected auxiliary space: O(h) , where h = height of tree
20 8 22 4 12 N N N N 10 14
20 7 24 4 3 N N N N 1
10 14 22
we can observe that target node is 8, and nodes which are at k distant from this target node are 10, 14 and 22.
If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.