1. Recursive DFS with (Depth, HD) Tracking
Intuition
Since DFS can visit lower nodes on one branch before higher nodes on another branch, storing map[HD] requires also storing the depth. If current depth >= stored depth, overwrite map[HD] = {val, depth}.
When to apply: Basic baseline check.
Algorithm
- Step 1: Helper dfs(node, hd, depth, map).
- Step 2: If node == null return.
- Step 3: If hd not in map or depth >= map[hd].depth: map[hd] = {val: node.val, depth}.
- Step 4: Recurse dfs(node.left, hd - 1, depth + 1) and dfs(node.right, hd + 1, depth + 1).
- Step 5: Sort map by hd and return values.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void dfs(TreeNode* node, int hd, int depth, map<int, pair<int, int>>& m) { if (!node) return; if (m.find(hd) == m.end() || depth >= m[hd].second) { m[hd] = {node->val, depth}; } dfs(node->left, hd - 1, depth + 1, m); dfs(node->right, hd + 1, depth + 1, m); } vector<int> bottomView(TreeNode* root) { map<int, pair<int, int>> m; dfs(root, 0, 0, m); vector<int> res; for (auto& p : m) res.push_back(p.second.first); return res; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n log n)— DFS takes O(n); sorting keys takes O(w log w) <= O(n log n). - Space complexity:
O(n)— Map stores entries for up to n nodes, plus O(h) recursion stack.