[Geeks for Geeks] Top View of Binary Tree

Top View of Binary Tree

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

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution
{
int mi = 0;
unordered_map<int, pair<int,int>> mp;
void helper(Node* node, int w, int dep = 0) {
if(!node) return;
mi = min(mi, w);
if(!mp.count(w) or mp[w].first > dep) mp[w] = {dep, node->data};

helper(node->left, w - 1, dep + 1);
helper(node->right, w + 1, dep + 1);
}
public:
//Function to return a list of nodes visible from the top view
//from left to right in Binary Tree.
vector<int> topView(Node *root)
{
helper(root, 0);
vector<int> res;
while(mp.count(mi)) {
res.push_back(mp[mi++].second);
}
return res;
}

};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/top-view-of-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.