180. Top View of BT

Given the root of a binary tree, return the top view of the binary tree.

The top view of a binary tree consists of the set of nodes visible when the tree is observed from above.

Return the values of these nodes ordered from the leftmost to the rightmost position.

If multiple nodes share the same horizontal distance from the root, only the node that appears first when traversing from left to right (i.e., the leftmost node) should be included in the result.

Example 1:

Input : root = [1, 2, 3, 4, 5, 6, 7]

Output : [4, 2, 1, 3, 7]

Explanation :

Example 2:

Input : root = [10, 20, 30, 40, 60, 90, 100]

Output : [40, 20, 10, 30, 100]

Explanation :

Now Your Turn!

Pick the correct output for the given input

Input : root = [5, 1, 2, 8, null, 4, 5, null, 6]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 104
  • -103 <= Node.val <= 103

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution{
public:
vector<int> topView(TreeNode *root){
//your code goes here
}
};
Test Case

Input:

Root