Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree
1
/ \
2 3
/ \ / \
4 5 6 7
Top view will be: 4 2 1 3 7
Note: Print from leftmost node to rightmost node.
Input Format:
First line of input contains the number of test cases T. For each test case, there will be two lines:
First line of each test case will be an integer N denoting the number of parent child relationships.
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 Format:
For each test case, in a new line, print top view of the binary tree level wise. The nodes should be separated by space.
Your Task:
Since this is a function problem. You don't have to take input. Just complete the function printTopView() that takes root node as parameter and prints the top view. The newline is automatically appended by the driver code.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N).
Constraints:
1 <= T <= 30
1 <= N <= 10^{5}
1 <= Node Data <= 10^{5}
Sum of all testcases doesn't exceed 10^{5}
Example:
Input:
2
2
1 2 L 1 3 R
6
10 20 L 10 30 R 20 40 L 20 60 R 30 90 L 30 100 R
Output:
2 1 3
40 20 10 30 100
Explanation:
Testcase 1:
1
/ \
2 3
For the above test case the top view is: 2 1 3
Test case 2:
10
/ \
20 30
/ \ / \
40 60 90 100
TopView is: 40 20 10 30 100
Note:The Input/Ouput format and Example given are used for 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 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.
abnandi04 | 801 |
KshamaGupta | 560 |
mummy | 322 |
NikhilGupta0301 | 260 |
jagseersinghbe18cse | 251 |
abnandi04 | 776 |
KshamaGupta | 444 |
mummy | 235 |
srivastavad270 | 223 |
bhavyapratap56 | 206 |
blackshadows | 5362 |
Ibrahim Nash | 5244 |
akhayrutdinov | 5111 |
mb1973 | 4976 |
Quandray | 4748 |