1. DFS with (Depth, HD) Tracking
Intuition
Traverse tree with DFS. Store (val, depth) in map. If HD not in map or depth < map[hd].depth, update. Sort keys at end.
When to apply: Basic baseline check.
Algorithm
- Step 1: Helper dfs(node, hd, depth, map).
- Step 2: If hd not in map or depth < map[hd].depth: map[hd] = (node.val, depth).
- Step 3: dfs(left, hd - 1, depth + 1); dfs(right, hd + 1, depth + 1).
- Step 4: Sort map keys 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.count(hd) || 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> topView(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 is O(n); sorting map keys takes O(w log w). - Space complexity:
O(n)— Map stores entries for up to n nodes.