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.
Input:
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.
Output:
All the space separated nodes that are at distance k from the given target node in sorted order.
Your task:
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.
Constraints:
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
Example:
Input:
2
20 8 22 4 12 N N N N 10 14
8
2
20 7 24 4 3 N N N N 1
7
2
Output:
10 14 22
1 24
Explanation:
Testcase 1:
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.
praneethmamidala83 | 583 |
pallavimanukonda8 | 563 |
a8haysingh | 451 |
vraamg | 432 |
RajatGarg5 | 386 |
descifrador | 1683 |
mantu_singh | 1520 |
rishabh2017 | 1273 |
gladiator121 | 1268 |
kid_kb | 1264 |
blackshadows | 5362 |
Ibrahim Nash | 5244 |
akhayrutdinov | 5111 |
mb1973 | 4974 |
Quandray | 4732 |