Top View of Binary Tree
Submissions: 19373   Accuracy:

32.3%

  Difficulty: Medium   Marks: 4

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: 1 2 3 4 7

Input Format:
The first line of the input contains a single integer T denoting the number of test cases. T testcases follow. Each testcase contains two lines of input. The first line contains number of edges. The second line contains relation between 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.

Constraints:
1 <= T <= 100
1 <= N <= 50

Example:
Input:

2
2
1 2 L 1 3 R
5
10 20 L 10 30 R 20 40 L 20 60 R 30 90 L

Output:
1 2 3
10 20 30 40

Explanation:
Testcase 1:

           1

        /     \

      2        3

For the above test case the top view is: 1 2 3
Test case 2:

            10

         /        \

     20          30

   /      \       /

40      60 90

TopView is: 10 20 30 40.
 

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

Contributor: Saksham Raj Seth, Harshit Sidhwa
Author: harshitsidhwa


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.