Nodes at given distance in binary tree
Submissions: 9986   Accuracy:

42.57%

  Difficulty: Hard   Marks: 8

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: 

  1. 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.

  2. For example:

    For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N

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.

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Ayush Govil
Author: Ayush Govil 1


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.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.


to report an issue on this page.