[Geeks for Geeks] Bottom View of Binary Tree

Bottom View of Binary Tree

Given a binary tree, print the bottom view from left to right.
A node is included in bottom view if it can be seen when we look at the tree from bottom.

  • 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

class Solution {
unordered_map<int, pair<int,int>> mp;
int mi = 0;
void helper(Node* root, int dep, int w) {
if(!root) return;
mi = min(w, mi);
if(mp[w].first <= dep) mp[w] = {dep, root->data};
helper(root->left, dep + 1, w - 1);
helper(root->right, dep + 1, w + 1);
}
public:
vector <int> bottomView(Node *root) {
helper(root, 1, 0);
vector<int> res;
while(mp.count(mi)) {
res.push_back(mp[mi].second);
mi++;
}

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