Bottom View of Binary Tree
Problem
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.
20
/ \
8 22
/ \ \
5 3 25
/ \
10 14
For the above tree, the bottom view is 5 10 3 14 25.
If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. For example, in the below diagram, 3 and 4 are both the bottommost nodes at horizontal distance 0, we need to print 4.
20
/ \
8 22
/ \ / \
5 3 4 25
/ \
10 14
For the above tree the output should be 5 10 4 14 25.
Your Task:
This is a functional problem, you don't need to care about input, just complete the function bottomView() which takes the root node of the tree as input and returns an array containing the bottom view of the given tree.
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
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> bottomView(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;
}
};