Top View of Binary Tree
Given a binary tree of integers, the task is to return the top view of the given binary tree. The top view of the binary tree is the set of nodes visible when viewed from the top.
Input:
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains elements of the tree in level-order format, with values separated by spaces. Use -1 to denote null nodes.
Output:
For each test case, return a list of integers representing the top view of the given tree.
Example:
For the given binary tree:
The top view of the tree will be {10, 4, 2, 1, 3, 6}.
Example Input:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Explanation:
Level 1: The root node is 1.
Level 2: Left child of 1 is 2, right child of 1 is 3.
Level 3: Left child of 2 is 4, right child is null (-1), left child of 3 is 5, right is 6.
Level 4: Right child of 4 is 7, all other children are null (-1).
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Constraints:
- 1 <= T <= 100
- 0 <= N <= 1000
- 0 <= data <= 10^6 and data != -1
Where ‘N’ is the total number of nodes, and 'data' is the value of the binary tree node.
Time limit: 1 sec
Note:
The input ends when all nodes at the last level are null (-1).
You don't need to print the output. Implement the function to return the answer.

AnswerBot
4mo
Return the top view of a binary tree given in level-order format.
Traverse the binary tree in level-order and keep track of the horizontal distance of each node from the root.
Use a map to store the nod...read more
Help your peers!
Add answer anonymously...
Blinkit Software Developer Intern interview questions & answers
A Software Developer Intern was asked Q. Top View of Binary Tree Given a binary tree of integers, the task is to return t...read more
A Software Developer Intern was asked Q. Maximum Possible Time Problem Statement Given an array ARR consisting of exactly...read more
A Software Developer Intern was asked Q. Sum of LCM Problem Statement Given an integer 'N', calculate and print the sum o...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked Q1. Maximum Possible Time Problem Statement Given an array ARR consisting of exactly...read more
A Software Developer Intern was asked Q2. Sum of LCM Problem Statement Given an integer 'N', calculate and print the sum o...read more
A Software Developer Intern was asked Q3. Vertical Order Traversal Problem Statement Given a binary tree, return the verti...read more
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

