07. Bottom View of Binary Tree
β GFG solution to the Bottom View of Binary Tree problem: find nodes visible from bottom using level order traversal and horizontal distance tracking. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given the root of a binary tree, and your task is to return its bottom view. The bottom view of a binary tree is the set of nodes visible when the tree is viewed from the bottom.
Note: If there are multiple bottom-most nodes for a horizontal distance from the root, then the latter one in the level order traversal is considered.
π Examples
Example 1
Input: root = [1, 2, 3, 4, 5, N, 6]
Output: [4, 2, 5, 3, 6]
Explanation: The nodes visible from the bottom view are 4, 2, 5, 3, and 6
based on their horizontal distances.
Example 2
Input: root = [20, 8, 22, 5, 3, 4, 25, N, N, 10, 14, N, N, 28, N]
Output: [5, 10, 4, 28, 25]
Explanation: These nodes are visible when viewing the tree from bottom,
considering horizontal distances and level order priority.
π Constraints
$1 \le \text{number of nodes} \le 10^5$
$1 \le \text{node->data} \le 10^5$
β
My Approach
The optimal approach uses Level Order Traversal (BFS) with Horizontal Distance Tracking using a map to efficiently find bottom view nodes:
BFS with Horizontal Distance Mapping
Initialize Data Structures:
Use a
map<int, int>
to store the mapping from horizontal distance to node value.Use a queue to perform level order traversal, storing pairs of
(Node*, horizontal_distance)
.Start with root at horizontal distance 0.
Perform Level Order Traversal:
Dequeue the front node and its horizontal distance.
Update the map with current node's data at its horizontal distance (overwrites previous value).
For left child: enqueue with
horizontal_distance - 1
.For right child: enqueue with
horizontal_distance + 1
.
Extract Bottom View:
The map automatically maintains sorted order of horizontal distances.
Since we process level by level and update the map, the last node at each horizontal distance represents the bottom view.
Extract all values from the map in order.
Return Result:
Convert map values to vector and return as the bottom view.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n log n), where n is the number of nodes in the binary tree. We visit each node once during BFS traversal (O(n)), and each map insertion/update operation takes O(log n) time due to the ordered map structure.
Expected Auxiliary Space Complexity: O(w), where w is the maximum width of the tree. The queue can hold at most w nodes at any level, and the map stores at most w entries for different horizontal distances.
π§βπ» Code (C++)
class Solution {
public:
vector<int> bottomView(Node* root) {
if (!root) return {};
map<int, int> m;
queue<pair<Node*, int>> q;
q.push({root, 0});
while (!q.empty()) {
auto [node, hd] = q.front();
q.pop();
m[hd] = node->data;
if (node->left) q.push({node->left, hd - 1});
if (node->right) q.push({node->right, hd + 1});
}
vector<int> res;
for (auto& [k, v] : m) res.push_back(v);
return res;
}
};
β Code (Java)
class Solution {
public ArrayList<Integer> bottomView(Node root) {
ArrayList<Integer> res = new ArrayList<>();
if (root == null) return res;
TreeMap<Integer, Integer> map = new TreeMap<>();
Queue<Pair> q = new LinkedList<>();
q.add(new Pair(root, 0));
while (!q.isEmpty()) {
Pair p = q.poll();
map.put(p.hd, p.node.data);
if (p.node.left != null) q.add(new Pair(p.node.left, p.hd - 1));
if (p.node.right != null) q.add(new Pair(p.node.right, p.hd + 1));
}
for (int val : map.values()) res.add(val);
return res;
}
class Pair {
Node node;
int hd;
Pair(Node n, int h) { node = n; hd = h; }
}
}
π Code (Python)
class Solution:
def bottomView(self, root):
if not root: return []
d = {}
q = deque([(root, 0)])
while q:
node, hd = q.popleft()
d[hd] = node.data
if node.left: q.append((node.left, hd - 1))
if node.right: q.append((node.right, hd + 1))
return [d[k] for k in sorted(d)]
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated