1. DFS with Level Index Map
Intuition
DFS with helper(node, level, id). Map level -> list of indices. Max width is max over all levels of (max(ids) - min(ids) + 1).
When to apply: Basic baseline check.
Algorithm
- Step 1: Traverse with DFS, storing heap coordinate id per level.
- Step 2: Track minId[level] and maxId[level].
- Step 3: Calculate maxId[level] - minId[level] + 1 for each level.
- Step 4: Return maximum width found.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution { unordered_map<int, unsigned long long> minId; unsigned long long maxW = 0; void dfs(TreeNode* node, int level, unsigned long long id) { if (!node) return; if (!minId.count(level)) minId[level] = id; maxW = max(maxW, id - minId[level] + 1); dfs(node->left, level + 1, 2 * id); dfs(node->right, level + 1, 2 * id + 1); }public: int widthOfBinaryTree(TreeNode* root) { dfs(root, 0, 1); return maxW; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Every node visited once. - Space complexity:
O(h)— Recursion call stack takes O(h).