Skip to main content

Top View of Binary Tree

Problem

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: Return nodes from leftmost node to rightmost node.

Your Task:
Since this is a function problem. You don't have to take input. Just complete the function topView() that takes root node as parameter and returns a list of nodes visible from the top view from left to right.

Solution Approach

Expected Time complexity: O(n)O(n)

Click - to see solution code
class Solution {
map<int, int> mp, height;

public:
void traversal(Node *root, int c, int h) {
if (!root) return;
if (height.find(c) == height.end() || height[c] > h) {
mp[c] = root->data;
height[c] = h;
}
traversal(root->left, c + 1, h + 1);
traversal(root->right, c - 1, h + 1);
}

vector<int> topView(Node *root) {
vector<int> view;
traversal(root, 0, 0);
for (auto i : mp) {
view.push_back(i.second);
}
reverse(view.begin(), view.end());
return view;
}
};