Given a Binary Tree and a number k. Print all nodes that are at distance k from root (root is considered at distance 0 from itself). Nodes should be printed from left to right. If k is more that height of tree, nothing should be printed.
For example, if below is given tree and k is 2. Output should be 4 5 6.
1
/ \
2 3
/ / \
4 5 6
\
8
Input:
First line of input contains the number of test cases T. For each test case, there will be two lines:
Second line of each test case will print the level order traversal of the tree in the form of N space separated triplets. The description of triplets is as follows:
Each triplet will contain three space-separated elements of the form (int, int char).
The first integer element will be the value of parent.
The second integer will be the value of corresponding left or right child. In case the child is null, this value will be -1.
The third element of triplet which is a character can take any of the three values ‘L’, ‘R’ or ‘N’. L denotes that the children is a left child, R denotes that the children is a Right Child and N denotes that the child is NULL.
Please note that the relationships are printed only for internal nodes and not for leaf nodes.
Output:
The function should print nodes at k distance from root. Nodes should be printed from left to right. If their is no node at distance k you don't need to print anything.
Your Task:
You don't have to take input. Complete the function printKdistance() that takes node and k as parameter and print the value of the nodes that are at a distance k from the root.
Constraints:
1 <= T <= 30
1 <= Number parent child relations <= 1000
1 <= Number of edges<= 1000
0 <= k <= 1000
1 <= data of node <= 1000
Example:
Input:
2
2 0
1 3 L 1 2 R
6 3
3 2 L 3 -1 N 2 -1 N 2 1 R 1 5 L 1 3 R
Output:
1
5 3
Explanation:
Testcase 1: First case represents a tree with 3 nodes, 2 edges and value of k as 0. Here root is 1, left child of 1 is 3 and right child of 1 is 2.
Testcase 2: Second test case represents a tree with 4 edges and 5 nodes and k as 3.
3
/
2
\
1
/ \
5 3
Note: The Input/Ouput format and Example is given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.
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.
akhyasharma01 | 467 |
ASWATHAMA | 399 |
john_wick | 360 |
mmzeineddine | 295 |
PiyushPandey4 | 271 |
PiyushPandey4 | 614 |
ASWATHAMA | 561 |
akhyasharma01 | 547 |
john_wick | 521 |
rahulnishad96 | 442 |
blackshadows | 5362 |
Ibrahim Nash | 5242 |
akhayrutdinov | 5111 |
mb1973 | 4929 |
Quandray | 4598 |