{"id":"maximum-level-sum-of-a-binary-tree","title":"Maximum Level Sum of a Binary Tree","difficulty":"medium","patterns":["tree-bfs"],"primaryConcept":"tree-bfs-basics","concepts":["tree-bfs-basics"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","description":"Given the root of a binary tree, return the smallest level number whose nodes have the maximum sum.\n\nThe root is on level 1. If multiple levels have the same maximum sum, return the smallest level number among them.","examples":[{"input":"root = {\"val\": 1, \"left\": {\"val\": 7, \"left\": {\"val\": 7}, \"right\": {\"val\": -8}}, \"right\": {\"val\": 0}}","output":"2","explanation":"Level 1 sums to 1, level 2 sums to 7, and level 3 sums to -1, so level 2 has the maximum sum."},{"input":"root = {\"val\": 5, \"left\": {\"val\": 2}, \"right\": {\"val\": 3}}","output":"1","explanation":"Levels 1 and 2 both sum to 5, so return the smaller level number: 1."},{"input":"root = {\"val\": -100, \"left\": {\"val\": -200, \"left\": {\"val\": -20}}, \"right\": {\"val\": -300, \"right\": {\"val\": -5}}}","output":"3","explanation":"All sums are negative, so the least negative sum wins. Level 3 sums to -25."}],"constraints":[{"id":"the-number-of-nodes-in-the-tree-is-in-the-range-1-10000","text":"The number of nodes in the tree is in the range [1, 10000].","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":1,"max":10000}},{"id":"100000-node-val-100000","text":"-100000 <= Node.val <= 100000","check":{"kind":"valueRange","target":"root","selector":"treeValues","min":-100000,"max":100000}}],"starterCode":"# TraceCode provides TreeNode at runtime.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\n\nclass Solution:\n    def maxLevelSum(self, root: TreeNode) -> int:\n        # Your code here\n        pass","functionName":"maxLevelSum","testCases":[{"id":"1","input":{"root":{"val":1,"left":{"val":7,"left":{"val":7,"left":null,"right":null,"__id__":"tree-3"},"right":{"val":-8,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-1"},"right":{"val":0,"left":null,"right":null,"__id__":"tree-2"},"__id__":"tree-0"}},"expected":2,"description":"Canonical case where the second level has the largest sum."},{"id":"2","input":{"root":{"val":5,"left":{"val":2,"left":null,"right":null,"__id__":"tree-1"},"right":{"val":3,"left":null,"right":null,"__id__":"tree-2"},"__id__":"tree-0"}},"expected":1,"description":"Tie between levels returns the smaller level number."},{"id":"3","input":{"root":{"val":-100,"left":{"val":-200,"left":{"val":-20,"left":null,"right":null,"__id__":"tree-3"},"right":null,"__id__":"tree-1"},"right":{"val":-300,"left":null,"right":{"val":-5,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":3,"description":"All negative values still compare level sums normally."},{"id":"4","input":{"root":{"val":1,"left":{"val":2,"left":{"val":3,"left":{"val":4,"left":null,"right":null,"__id__":"tree-3"},"right":null,"__id__":"tree-2"},"right":null,"__id__":"tree-1"},"right":null,"__id__":"tree-0"}},"expected":4,"description":"A skewed tree has one node per level."},{"id":"5","input":{"root":{"val":10,"left":{"val":1,"left":{"val":10,"left":null,"right":null,"__id__":"tree-3"},"right":{"val":10,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-1"},"right":{"val":2,"left":null,"right":{"val":10,"left":null,"right":null,"__id__":"tree-5"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":3,"description":"A deeper row can have the maximum sum."},{"id":"6","input":{"root":{"val":42,"left":null,"right":null,"__id__":"tree-0"}},"expected":1,"description":"Single-node tree."},{"id":"h1","input":{"root":{"val":-1,"left":{"val":-100000,"left":null,"right":null,"__id__":"tree-1"},"right":{"val":100000,"left":{"val":-100000,"left":null,"right":null,"__id__":"tree-3"},"right":{"val":100000,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":2,"description":"Boundary values and mixed signs."},{"id":"h2","input":{"root":{"val":-5,"left":{"val":-6,"left":null,"right":null,"__id__":"tree-1"},"right":{"val":-7,"left":null,"right":null,"__id__":"tree-2"},"__id__":"tree-0"}},"expected":1,"description":"The root level is the maximum when lower levels are more negative."},{"id":"h3","input":{"root":{"val":2,"left":{"val":1,"left":{"val":1,"left":null,"right":null,"__id__":"tree-3"},"right":null,"__id__":"tree-1"},"right":{"val":1,"left":null,"right":{"val":1,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":1,"description":"Later ties do not replace an earlier best level."},{"id":"h4","input":{"root":{"val":1,"left":{"val":2,"left":{"val":4,"left":null,"right":null,"__id__":"tree-3"},"right":null,"__id__":"tree-1"},"right":{"val":3,"left":null,"right":{"val":1,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":2},{"id":"deep-level-beats-mixed-second-level","input":{"root":{"val":1,"left":{"val":-2,"left":{"val":4,"left":null,"right":null,"__id__":"tree-3"},"right":{"val":5,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-1"},"right":{"val":3,"left":{"val":-6,"left":null,"right":null,"__id__":"tree-5"},"right":{"val":2,"left":null,"right":null,"__id__":"tree-6"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":3,"description":"A deeper level can beat mixed positive and negative sums above it."},{"id":"tie-between-lower-levels","input":{"root":{"val":-10,"left":{"val":5,"left":{"val":4,"left":null,"right":null,"__id__":"tree-3"},"right":null,"__id__":"tree-1"},"right":{"val":5,"left":null,"right":{"val":6,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":2,"description":"When lower levels tie, the smaller level number remains the answer."}],"hints":[{"level":1,"content":"The answer depends on whole tree rows, not individual root-to-leaf paths.","revealPattern":false},{"level":2,"content":"Use a queue and capture the current queue width before processing a level.","revealPattern":true},{"level":3,"content":"Track the current level number, reset a level sum for each row, and update the best level only when the new sum is strictly larger.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"bfs-level-sum","name":"BFS level sum","summary":"Use a queue, capture the current level size, sum exactly those nodes, and update the best level after each row.","decisionReason":"Capturing the queue length before each level isolates exactly the nodes on that level, so the running sum cannot mix children into their parent row. Updating best only after the level finishes preserves the smallest level on ties.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":true,"steps":["Seed the queue with the root.","Capture the current frontier size before processing a level.","Sum exactly that many nodes and enqueue their children.","Update the best level only when the completed level sum is strictly larger."]},{"id":"dfs-depth-buckets","name":"DFS depth buckets","summary":"Traverse recursively, add each node value into a sum bucket for its depth, then scan the buckets.","decisionReason":"Depth-indexed DFS computes the same level sums in O(n) time. The trace uses a queue so each level closes in order and its sum can be compared immediately.","complexity":{"time":"O(n)","space":"O(h + d)"},"tradeoffs":["Runs in O(n) time and uses O(h + d) space."],"isViable":true,"isOptimal":false,"steps":["Visit each node with a depth value.","Add its value into that depth's sum bucket.","Scan the depth sums to find the smallest maximum level."]}]},"codingCheckpoints":[{"id":"init-structures","title":"Seed the BFS queue","description":"Create the traversal queue and initialize the best-level tracking state.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_bfs_result_and_queue","scope":"init-structures","readMode":"tree-value-query-v1"}]},"commonMistakes":["Forgetting to enqueue the root","Starting the level counter at zero"],"hint":"Start with one frontier containing the root and set the current level to 1.","semanticSpec":{"intent":"Initialize the BFS frontier and the state that will remember the best level.","doneWhen":"A queue-like frontier is seeded with the root and answer-tracking state is initialized before traversal.","shouldFailWhen":"The root is never inserted into a queue-like frontier or there is no best-level state.","roles":["root node","BFS queue","current level","best level"],"mustProve":["The root node is inserted into a queue-like frontier.","The solution initializes state for the current level and the best answer."],"mustNotAccept":["Traversing from an empty queue.","Only storing a level sum without any answer level."],"equivalentVariants":["Use a list-backed queue with a head index.","Use a deque seeded with the root."],"proofSnippets":[{"id":"py-max-level-sum-init","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]"}]}},{"id":"while-loop","title":"Loop while the frontier has nodes","description":"Continue processing levels until the queue frontier is exhausted.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"loops_while_bfs_frontier_non_empty","scope":"while-loop","readMode":"tree-value-query-v1"}]},"commonMistakes":["Using a single pass instead of a frontier loop","Stopping before all queued children are processed"],"hint":"The outer loop should be driven by whether unprocessed queue entries remain.","semanticSpec":{"intent":"Drive traversal from the BFS frontier until every enqueued tree node has been processed.","doneWhen":"The outer loop continues while the queue has unprocessed nodes.","shouldFailWhen":"The code processes only the root or uses a loop unrelated to the queue frontier.","roles":["BFS queue","head cursor","frontier loop"],"mustProve":["The traversal loop is controlled by the queue frontier.","The loop can continue after child nodes are enqueued."],"mustNotAccept":["Only one level is processed.","A loop bound that ignores newly enqueued children."],"equivalentVariants":["Use `while head < len(queue)` for a list-backed queue.","Use `while queue` for a deque."],"proofSnippets":[{"id":"py-max-level-sum-while-loop","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]\n        head = 0\n        best_level = 1\n        while head < len(queue):\n            node = queue[head]\n            head += 1\n            if node.left:\n                queue.append(node.left)\n            if node.right:\n                queue.append(node.right)\n        return best_level"}]}},{"id":"level-size","title":"Capture the level size","description":"Freeze the number of nodes in the current level before enqueueing children.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"captures_bfs_level_boundary","scope":"level-size","readMode":"tree-value-query-v1"}]},"commonMistakes":["Using the changing queue length inside the inner loop","Mixing current-level and next-level nodes in the same sum"],"hint":"Store the current frontier width before the inner loop starts.","semanticSpec":{"intent":"Separate the current level from children that will belong to the next level.","doneWhen":"The current queue width is captured at the start of each level iteration.","shouldFailWhen":"The inner loop is allowed to grow as children are appended.","roles":["BFS queue","level size","frontier boundary"],"mustProve":["The outer loop is queue-driven.","The current level width is stored before processing level nodes."],"mustNotAccept":["No stable boundary between current and next level.","Using the live queue length as the inner-loop bound."],"equivalentVariants":["Store `len(queue) - head` for a list-backed queue.","Store `len(queue)` before dequeuing a deque level."],"proofSnippets":[{"id":"py-max-level-sum-capture-size","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            level_size = len(queue) - head\n            for _ in range(level_size):\n                node = queue[head]\n                head += 1\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            break\n        return 1"}]}},{"id":"process-level","title":"Accumulate the level sum","description":"Consume the captured number of nodes, add their values into the current level sum, and enqueue their children for later levels.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"updates_level_aggregate_from_node_value","scope":"update-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Forgetting to add every node value","Processing children in the same level where they are discovered","Forgetting to enqueue children"],"hint":"The inner loop is bounded by the captured level size, and children are appended for future levels.","semanticSpec":{"intent":"Accumulate the current level's node values while preparing the next frontier.","doneWhen":"A bounded inner loop adds processed node values into the level sum and appends child links to the queue.","shouldFailWhen":"The code skips value accumulation, never enqueues children, or lets the inner loop grow with the queue.","roles":["level nodes","level sum","aggregate update","child frontier"],"mustProve":["The inner loop is bounded by the captured level size.","Each processed node contributes to the level sum.","Child links are enqueued for later levels."],"mustNotAccept":["Accumulating without a stable level boundary.","Processing without enqueueing children.","Enqueueing children without advancing through current nodes."],"equivalentVariants":["Use a head-index queue.","Use dequeue operations from a FIFO queue."],"proofSnippets":[{"id":"py-max-level-sum-process-level","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]\n        head = 0\n        result = []\n        while head < len(queue):\n            level_size = len(queue) - head\n            level_sum = 0\n            for _ in range(level_size):\n                node = queue[head]\n                head += 1\n                level_sum += node.val\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            result.append(level_sum)\n            break"}]}},{"id":"return-best-level","title":"Return the best level","description":"Return the level number whose completed level sum was largest.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_level_aggregate_result","scope":"return-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning the maximum sum instead of its level","Returning the current level after it has advanced past the answer"],"hint":"Return the stored level number for the largest completed sum.","semanticSpec":{"intent":"Return the answer state produced by the completed level aggregate comparisons.","doneWhen":"The terminal return uses the best-level state updated after processing each level.","shouldFailWhen":"The function returns the queue, current level counter, or best sum instead of the stored answer level.","roles":["best level","best sum","terminal return"],"mustProve":["The best-level state is updated from completed level sums.","The terminal return reads the best-level answer."],"mustNotAccept":["Returning the maximum level sum.","Returning the current loop counter after traversal.","Returning the active queue."],"equivalentVariants":["Return a scalar `best_level`.","Return the level field from a best-answer pair."],"proofSnippets":[{"id":"py-max-level-sum-return-best","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]\n        head = 0\n        level = 1\n        best_level = 1\n        best_sum = -10**18\n        while head < len(queue):\n            level_size = len(queue) - head\n            level_sum = 0\n            for _ in range(level_size):\n                node = queue[head]\n                head += 1\n                level_sum += node.val\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            if level_sum > best_sum:\n                best_sum = level_sum\n                best_level = level\n            level += 1\n        return best_level"}]}}],"slides":[{"id":"opener","chapter":"The task","kind":"info","eyebrow":"Read the problem","title":"Which whole row sums largest","workspacePanel":"problem","body":["A binary tree stacks its nodes in rows by depth, and the root is row 1. Add up every value in a row, compare those row totals, and return the number of the row whose total is largest. When two rows tie, return the smaller row number.","Values can be negative, so a wide, crowded row can total less than a row holding one small positive node. No row's total is knowable without summing all of it."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"opener-state","state":{"tree":[1,7,0,7,-8],"swapped":[1,2]}}]}},{"id":"bucket-rows","chapter":"The obvious way","kind":"code-trace","eyebrow":"Start with the naive way","title":"Bucket every node into its depth's sum, then scan","summary":"The answer is one total per depth, so the plainest version walks the whole tree once, adding each node's value into a running sum for its own depth. Once every node is filed, a second loop scans those depth sums to find the largest.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def maxLevelSum(root: TreeNode) -> int:\n    sums = []\n    nodes = [root]\n    depths = [0]\n    while nodes:\n        node = nodes.pop()\n        depth = depths.pop()\n        if depth == len(sums):\n            sums.append(0)\n        sums[depth] += node.val\n        if node.right:\n            nodes.append(node.right)\n            depths.append(depth + 1)\n        if node.left:\n            nodes.append(node.left)\n            depths.append(depth + 1)\n    best_level = 1\n    best_sum = sums[0]\n    for i in range(1, len(sums)):\n        if sums[i] > best_sum:\n            best_sum = sums[i]\n            best_level = i + 1\n    return best_level","steps":[{"id":"bucket-root","title":"File the root under depth 0","codeLine":10,"summary":"The walk reads 1 and adds it into the depth-0 sum. sums now holds [1].","state":{"tree":[1,7,0,7,-8],"node":0}},{"id":"bucket-fill","title":"Every node lands in its depth's sum","codeLine":10,"summary":"The walk keeps going until 7 and 0 add into depth 1 and 7 and -8 add into depth 2. sums holds [1, 7, -1], one total per row, but only after the whole tree is read.","state":{"tree":[1,7,0,7,-8],"visited":[0],"swapped":[1,2,3,4]}},{"id":"bucket-scan","title":"Only now, scan the depth sums for the largest","codeLine":20,"summary":"With every total already in memory, a second sweep compares 1, 7, and -1. The largest is 7 at depth 1, which is row 2, so best_level becomes 2.","state":{"tree":[1,7,0,7,-8],"visited":[0,1,2,3,4],"swapped":[1,2]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const sums = [];\nconst nodes = [root];\nconst depths = [0];\nwhile (nodes.length > 0) {\n    const node = nodes.pop();\n    const depth = depths.pop();\n    if (depth == sums.length) {\n        sums.push(0);\n    }\n    sums[depth] = (sums[depth] + node.val);\n    if (node.right) {\n        nodes.push(node.right);\n        depths.push((depth + 1));\n    }\n    if (node.left) {\n        nodes.push(node.left);\n        depths.push((depth + 1));\n    }\n}\nlet bestLevel = 1;\nlet bestSum = sums[0];\nfor (let i = 1; i < sums.length; i++) {\n    if (sums[i] > bestSum) {\n        bestSum = sums[i];\n        bestLevel = i + 1;\n    }\n}\nreturn bestLevel;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":10,"11":11,"12":12,"13":13,"14":15,"15":16,"16":17,"17":20,"18":21,"19":22,"20":23,"21":24,"22":25,"23":28},"statementBundles":{"9":{"startLine":8,"endLine":9},"13":{"startLine":13,"endLine":14},"16":{"startLine":17,"endLine":19},"22":{"startLine":25,"endLine":27}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const sums: Array<number> = [];\nconst nodes = [root];\nconst depths = [0];\nwhile (nodes.length > 0) {\n    const node = nodes.pop()!;\n    const depth = depths.pop()!;\n    if (depth == sums.length) {\n        sums.push(0);\n    }\n    sums[depth] = (sums[depth] + node.val);\n    if (node.right) {\n        nodes.push(node.right);\n        depths.push((depth + 1));\n    }\n    if (node.left) {\n        nodes.push(node.left);\n        depths.push((depth + 1));\n    }\n}\nlet bestLevel = 1;\nlet bestSum = sums[0];\nfor (let i = 1; i < sums.length; i++) {\n    if (sums[i] > bestSum) {\n        bestSum = sums[i];\n        bestLevel = i + 1;\n    }\n}\nreturn bestLevel;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":10,"11":11,"12":12,"13":13,"14":15,"15":16,"16":17,"17":20,"18":21,"19":22,"20":23,"21":24,"22":25,"23":28},"statementBundles":{"9":{"startLine":8,"endLine":9},"13":{"startLine":13,"endLine":14},"16":{"startLine":17,"endLine":19},"22":{"startLine":25,"endLine":27}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> sums = new();\nList<TreeNode> nodes = new() { root };\nList<int> depths = new() { 0 };\nwhile (nodes.Count > 0) {\n    TreeNode node = nodes[nodes.Count - 1];\n    nodes.RemoveAt(nodes.Count - 1);\n    int depth = depths[depths.Count - 1];\n    depths.RemoveAt(depths.Count - 1);\n    if (depth == sums.Count) {\n        sums.Add(0);\n    }\n    sums[depth] = sums[depth] + node.val;\n    if (node.right != null) {\n        nodes.Add(node.right);\n        depths.Add(depth + 1);\n    }\n    if (node.left != null) {\n        nodes.Add(node.left);\n        depths.Add(depth + 1);\n    }\n}\nint bestLevel = 1;\nint bestSum = sums[0];\nfor (int i = 1; i < sums.Count; i++) {\n    if (sums[i] > bestSum) {\n        bestSum = sums[i];\n        bestLevel = i + 1;\n    }\n}\nreturn bestLevel;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":9,"9":10,"10":12,"11":13,"12":14,"13":15,"14":17,"15":18,"16":19,"17":22,"18":23,"19":24,"20":25,"21":26,"22":27,"23":30},"statementBundles":{"6":{"startLine":5,"endLine":6},"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":11},"13":{"startLine":15,"endLine":16},"16":{"startLine":19,"endLine":21},"22":{"startLine":27,"endLine":29}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> sums;\nvector<TreeNode*> nodes{root};\nvector<int> depths{0};\nwhile (!nodes.empty()) {\n    TreeNode* node = nodes.back();\n    nodes.pop_back();\n    int depth = depths.back();\n    depths.pop_back();\n    if (depth == sums.size()) {\n        sums.push_back(0);\n    }\n    sums[depth] = (sums[depth] + node->val);\n    if (node->right) {\n        nodes.push_back(node->right);\n        depths.push_back((depth + 1));\n    }\n    if (node->left) {\n        nodes.push_back(node->left);\n        depths.push_back((depth + 1));\n    }\n}\nint best_level = 1;\nint best_sum = sums[0];\nfor (int i = 1; i < sums.size(); i++) {\n    if (sums[i] > best_sum) {\n        best_sum = sums[i];\n        best_level = i + 1;\n    }\n}\nreturn best_level;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":9,"9":10,"10":12,"11":13,"12":14,"13":15,"14":17,"15":18,"16":19,"17":22,"18":23,"19":24,"20":25,"21":26,"22":27,"23":30},"statementBundles":{"6":{"startLine":5,"endLine":6},"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":11},"13":{"startLine":15,"endLine":16},"16":{"startLine":19,"endLine":21},"22":{"startLine":27,"endLine":29}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> sums = new ArrayList<>();\nList<TreeNode> nodes = new ArrayList<>(List.of(root));\nList<Integer> depths = new ArrayList<>(List.of(0));\nwhile (!nodes.isEmpty()) {\n    TreeNode node = nodes.remove(nodes.size() - 1);\n    int depth = depths.remove(depths.size() - 1);\n    if (depth == sums.size()) {\n        sums.add(0);\n    }\n    sums.set(depth, (sums.get(depth) + node.val));\n    if (node.right != null) {\n        nodes.add(node.right);\n        depths.add(depth + 1);\n    }\n    if (node.left != null) {\n        nodes.add(node.left);\n        depths.add(depth + 1);\n    }\n}\nint bestLevel = 1;\nint bestSum = sums.get(0);\nfor (int i = 1; i < sums.size(); i++) {\n    if (sums.get(i) > bestSum) {\n        bestSum = sums.get(i);\n        bestLevel = i + 1;\n    }\n}\nreturn bestLevel;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":10,"11":11,"12":12,"13":13,"14":15,"15":16,"16":17,"17":20,"18":21,"19":22,"20":23,"21":24,"22":25,"23":28},"statementBundles":{"9":{"startLine":8,"endLine":9},"13":{"startLine":13,"endLine":14},"16":{"startLine":17,"endLine":19},"22":{"startLine":25,"endLine":27}}}}}},{"id":"bucket-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Read the state shape","title":"When does a row's total actually become final?","workspacePanel":"trace","summary":"The baseline runs in two phases: the walk files every node into a sum for its depth, then a second loop compares those stored sums. Look at when each depth's total stops changing versus when it gets compared.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bucket-cost-settled","state":{"tree":[1,7,0,7,-8],"visited":[0,1,2,3,4]}}]},"options":[{"id":"cost-all-depths","label":"Each depth's total is final once that row is fully read, but the compare waits until the whole walk ends","rationale":"A row's sum stops changing the moment its last node is filed, so it could be judged right then. But this baseline compares nothing until the second loop, so every settled total sits unused in sums until the walk is over.","isCorrect":true},{"id":"cost-one-depth","label":"A row's total is only final once the deepest row is reached, so nothing can be compared earlier","rationale":"A row's total is settled as soon as its own last node is read, regardless of what is deeper. The deeper rows do not change a shallower row's sum, so the compare could happen the moment that row closes.","isCorrect":false},{"id":"cost-one-number","label":"Each total is final only after the second loop reads it","rationale":"The second loop only reads totals that were already settled during the walk; it does not finalize them. The values stopped changing as each row finished, well before the compare.","isCorrect":false}],"answer":"A level's sum is finished the moment its last node is read, so it could be compared right then instead of waiting. The baseline holds every settled total at once only because it postpones all comparison to a second loop. A traversal that closes one row at a time can compare and discard each total as it finishes."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","title":"Which traversal finishes one row's sum before the next?","eyebrow":"Pick the route","summary":"Comparing a row's total needs that row's nodes gathered together before the next row mixes in. The two traversals differ in how easily a row is held as a unit.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"tree":[1,7,0,7,-8]}}]},"selection":{"contract":"approach-selection-v1","question":"Which traversal finishes one row's sum before the next?","decisionPrompt":"Both are O(n) and correct, so neither wins on complexity. We want to compare a row as soon as it is complete. Which traversal naturally exposes a whole row before its children are processed?","approaches":[{"id":"bfs-level-sum","name":"Queue by arrival order","summary":"Reach nodes oldest first, adding each node's children to the back of the line, so a whole row waits in the queue together before any of its children arrive.","decisionReason":"This is what the lesson practices: reaching nodes oldest-first means one row sits in the queue as a frontier you can total in a single pass, then compare immediately and discard. The row boundary falls out of the frontier width, and the winning row stays decided as you go. It does not beat DFS on complexity, it just makes the row total the thing you finish and compare.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space for the widest row; same time as DFS, and the space comparison flips with tree shape."],"isOptimal":true,"steps":["Seed a queue with the root and start the level counter at 1.","Snapshot the current frontier width before processing it.","Sum exactly those nodes, enqueue their children, then compare that row's total against the best so far."]},{"id":"dfs-depth-buckets","name":"Depth-indexed recursion","summary":"Recurse through the tree carrying each node's depth, and keep a running sum per depth in a list indexed by depth.","decisionReason":"Depth-indexed DFS computes the same level sums in O(n) time. The trace uses a queue so each level closes in order and its sum can be compared immediately.","complexity":{"time":"O(n)","space":"O(h + d)"},"tradeoffs":["Runs in O(n) time and uses O(h + d) space for the recursion and one slot per depth; can use less space than BFS on a wide, shallow tree."],"isViable":true,"isOptimal":false,"steps":["Visit each node carrying its depth.","Add its value into the stored sum for that depth.","Scan the depth sums for the largest after the traversal."]}]}},{"id":"trace-setup","chapter":"Trace","kind":"info","eyebrow":"Set up the sweep","title":"Fan the tree out by row with a queue","workspacePanel":"visualizer","body":["Seed a queue with the root, then each pass reads the nodes already waiting in it, oldest first, and appends each node's children to the back, behind everything still unread. Call the running total for the row being read its level sum.","Keep two pieces of memory as you go: the best level sum seen so far and the level number that produced it. After each row finishes, compare its level sum against the best.","On the tree, row 1 holds 1, row 2 holds 7 and 0, and row 3 holds 7 and -8. Predict the total each row hands up and which level ends up best."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"trace-setup-state","state":{"tree":[1,7,0,7,-8],"node":0,"swapped":[1,2]}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","title":"Sweep three rows","eyebrow":"Trace the sweep","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"beat-row1","state":{"tree":[1,7,0,7,-8],"node":0,"visited":[0]}},{"id":"beat-row2-bound","state":{"tree":[1,7,0,7,-8],"visited":[0],"swapped":[1,2]}},{"id":"beat-row2-sum","state":{"tree":[1,7,0,7,-8],"visited":[0],"swapped":[1,2]}},{"id":"beat-row3-sum","state":{"tree":[1,7,0,7,-8],"visited":[0,1,2],"swapped":[3,4]}}]},"beats":[{"id":"beat-row1","title":"Row 1 holds only the root. Which level is best so far?","summary":"The queue holds just the root 1, so row 1 sums to 1, the first total seen.","options":[{"id":"r1-level1","label":"Level 1, since it is the only row finished","rationale":"Row 1's sum of 1 is the first total, so nothing can have beaten it yet. The best level is 1 with best sum 1, ready to be challenged by later rows.","isCorrect":true},{"id":"r1-wait","label":"No level yet, wait for a positive enough sum","rationale":"Every finished row competes, including the first. Row 1 sets the standing best at level 1, sum 1.","isCorrect":false},{"id":"r1-level2","label":"Level 2, since its children 7 and 0 look larger","rationale":"Row 2 has not been summed yet; its children are still unread in the queue. Only finished rows can take the lead, and so far only row 1 is done.","isCorrect":false}],"answer":"Row 1 sums to 1, the first total, so the best level is 1 with best sum 1."},{"id":"beat-row2-bound","title":"Children pile up behind. How many nodes belong to row 2?","summary":"Reading each waiting node enqueues its children right behind it, so decide which nodes belong to the row before those children mix in.","options":[{"id":"r2-two","label":"Exactly the two nodes waiting when the pass began","rationale":"Two nodes, 7 and 0, were queued at the start of the pass. Fix that count first, sum exactly those two, and any children added during the pass wait for the next row.","isCorrect":true},{"id":"r2-drain","label":"Everything in the queue until it empties","rationale":"The children of 7 enter the queue during the pass. Draining it pulls 7 and -8 into row 2 as well, merging two rows into one sum.","isCorrect":false},{"id":"r2-one","label":"Just the first node, 7, then move on","rationale":"Stopping at 7 misses 0, still waiting in the same row. A row's sum needs every node at the depth.","isCorrect":false}],"answer":"Lock in the width, two, before the pass, so 7 and -8 stay in row 3 even as they pile up behind."},{"id":"beat-row2-sum","title":"Which level is best after row 2?","summary":"Row 2 is the two nodes just swept, 7 and 0. The standing best so far came from row 1.","options":[{"id":"r2-level2","label":"Level 2, because 7 is larger than 1","rationale":"Row 2 sums to 7, which beats the standing best sum of 1, so the best level moves to 2 with best sum 7.","isCorrect":true},{"id":"r2-level1","label":"Level 1, since it was first","rationale":"Being first only holds the lead until a strictly larger sum arrives. 7 is larger than 1, so level 2 takes over.","isCorrect":false},{"id":"r2-sum7","label":"7, the sum itself","rationale":"7 is the level sum, but the answer tracks the level number that produced it. That level is 2.","isCorrect":false}],"answer":"Row 2's sum of 7 beats the best sum of 1, so the best level becomes 2."},{"id":"beat-row3-sum","title":"What is the final answer after row 3?","summary":"Row 3 is the last two nodes swept, 7 and -8. The standing best so far came from row 2.","options":[{"id":"r3-level2","label":"Level 2, because -1 does not beat 7","rationale":"Row 3 sums to -1, which is below the best sum of 7, so the best level stays 2. The queue empties after, so the final answer is 2.","isCorrect":true},{"id":"r3-level3","label":"Level 3, since it was processed last","rationale":"Being last does not win it. Row 3's sum of -1 is smaller than 7, so level 2 keeps the lead.","isCorrect":false},{"id":"r3-level1","label":"Level 1, falling back to the first row","rationale":"The best level only moves forward on a larger sum; it never falls back. Level 2 held sum 7 and nothing beat it.","isCorrect":false}],"answer":"Row 3 sums to -1, which does not beat 7, so the best level stays 2 and the answer is 2."}]},{"id":"tie-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Should a row update the best when its sum just ties?","summary":"Taking over the lead whenever a row's sum is at least as large as the best, comparing with greater-or-equal, slips past every test where one row clearly wins. Watch what happens on a tree where two rows tie.","workspacePanel":"trace","pitfall":"The loop below updates the best level whenever the row sum is greater than or equal to the best sum, instead of strictly greater.","whyItMatters":"Update the best only on a strictly larger sum. Once equality counts, a later tied row overwrites the earlier best level, so a tie reports the larger level number when the problem asks for the smaller one.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def maxLevelSum(root: TreeNode) -> int:\n    queue = [root]\n    head = 0\n    level = 1\n    best_level = 1\n    best_sum = -2147483648\n    while head < len(queue):\n        level_size = len(queue) - head\n        level_sum = 0\n        count = 0\n        while count < level_size:\n            node = queue[head]\n            head += 1\n            count += 1\n            level_sum += node.val\n            if node.left:\n                queue.append(node.left)\n            if node.right:\n                queue.append(node.right)\n        if level_sum >= best_sum:\n            best_sum = level_sum\n            best_level = level\n        level += 1\n    return best_level","steps":[{"id":"tie-row1","title":"Row 1 sets the best to level 1","codeLine":19,"summary":"On the tree with root 5 and children 2 and 3, row 1 sums to 5. It beats the sentinel, so best_level is 1 and best_sum is 5. So far this matches a correct sweep.","state":{"tree":[5,2,3],"node":0,"visited":[0]}},{"id":"tie-row2-sum","title":"Row 2 sums to 5 as well","codeLine":14,"summary":"Row 2 holds 2 and 3, which add to 5. That equals the best sum of 5 rather than exceeding it.","state":{"tree":[5,2,3],"visited":[0],"swapped":[1,2]}},{"id":"tie-overwrite","title":"Greater-or-equal lets the tie take over","codeLine":19,"summary":"Because 5 is greater than or equal to 5, the check passes and best_level is overwritten from 1 to 2, even though no row beat the earlier total.","state":{"tree":[5,2,3],"node":2,"visited":[0,1,2],"swapped":[1,2]}},{"id":"tie-wrong","title":"The tie reported the larger level","codeLine":23,"summary":"The function returns 2, but rows 1 and 2 tie at 5 and the problem asks for the smaller level number, 1.","state":{"tree":[5,2,3],"visited":[0,1,2],"swapped":[0]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const queue = [root];\nlet head = 0;\nlet level = 1;\nlet bestLevel = 1;\nlet bestSum = -2147483648;\nwhile (head < queue.length) {\n    const levelSize = queue.length - head;\n    let levelSum = 0;\n    let count = 0;\n    while (count < levelSize) {\n        const node = queue[head];\n        head++;\n        count++;\n        levelSum += node.val;\n        if (node.left) {\n            queue.push(node.left);\n        }\n        if (node.right) {\n            queue.push(node.right);\n        }\n    }\n    if (levelSum >= bestSum) {\n        bestSum = levelSum;\n        bestLevel = level;\n    }\n    level++;\n}\nreturn bestLevel;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":11,"13":12,"14":13,"15":14,"16":15,"17":16,"18":18,"19":19,"20":22,"21":23,"22":24,"23":26,"24":28},"statementBundles":{"17":{"startLine":16,"endLine":17},"19":{"startLine":19,"endLine":21},"22":{"startLine":24,"endLine":25},"23":{"startLine":26,"endLine":27}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const queue = [root];\nlet head = 0;\nlet level = 1;\nlet bestLevel = 1;\nlet bestSum = -2147483648;\nwhile (head < queue.length) {\n    const levelSize = queue.length - head;\n    let levelSum = 0;\n    let count = 0;\n    while (count < levelSize) {\n        const node = queue[head];\n        head++;\n        count++;\n        levelSum += node.val;\n        if (node.left) {\n            queue.push(node.left);\n        }\n        if (node.right) {\n            queue.push(node.right);\n        }\n    }\n    if (levelSum >= bestSum) {\n        bestSum = levelSum;\n        bestLevel = level;\n    }\n    level++;\n}\nreturn bestLevel;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":11,"13":12,"14":13,"15":14,"16":15,"17":16,"18":18,"19":19,"20":22,"21":23,"22":24,"23":26,"24":28},"statementBundles":{"17":{"startLine":16,"endLine":17},"19":{"startLine":19,"endLine":21},"22":{"startLine":24,"endLine":25},"23":{"startLine":26,"endLine":27}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<TreeNode> queue = new() { root };\nint head = 0;\nint level = 1;\nint bestLevel = 1;\nint bestSum = -2147483648;\nwhile (head < queue.Count) {\n    int levelSize = queue.Count - head;\n    int levelSum = 0;\n    int count = 0;\n    while (count < levelSize) {\n        TreeNode node = queue[head];\n        head++;\n        count++;\n        levelSum += node.val;\n        if (node.left != null) {\n            queue.Add(node.left);\n        }\n        if (node.right != null) {\n            queue.Add(node.right);\n        }\n    }\n    if (levelSum >= bestSum) {\n        bestSum = levelSum;\n        bestLevel = level;\n    }\n    level++;\n}\nreturn bestLevel;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":11,"13":12,"14":13,"15":14,"16":15,"17":16,"18":18,"19":19,"20":22,"21":23,"22":24,"23":26,"24":28},"statementBundles":{"17":{"startLine":16,"endLine":17},"19":{"startLine":19,"endLine":21},"22":{"startLine":24,"endLine":25},"23":{"startLine":26,"endLine":27}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<TreeNode*> queue{root};\nsize_t head = 0;\nint level = 1;\nint best_level = 1;\nint best_sum = -2147483648;\nwhile (head < queue.size()) {\n    int level_size = queue.size() - head;\n    int level_sum = 0;\n    int count = 0;\n    while (count < level_size) {\n        TreeNode* node = queue[static_cast<int>(head)];\n        head++;\n        count++;\n        level_sum += node->val;\n        if (node->left) {\n            queue.push_back(node->left);\n        }\n        if (node->right) {\n            queue.push_back(node->right);\n        }\n    }\n    if (level_sum >= best_sum) {\n        best_sum = level_sum;\n        best_level = level;\n    }\n    level++;\n}\nreturn best_level;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":11,"13":12,"14":13,"15":14,"16":15,"17":16,"18":18,"19":19,"20":22,"21":23,"22":24,"23":26,"24":28},"statementBundles":{"17":{"startLine":16,"endLine":17},"19":{"startLine":19,"endLine":21},"22":{"startLine":24,"endLine":25},"23":{"startLine":26,"endLine":27}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<TreeNode> queue = new ArrayList<>(List.of(root));\nint head = 0;\nint level = 1;\nint bestLevel = 1;\nint bestSum = -2147483648;\nwhile (head < queue.size()) {\n    int levelSize = queue.size() - head;\n    int levelSum = 0;\n    int count = 0;\n    while (count < levelSize) {\n        TreeNode node = queue.get(head);\n        head++;\n        count++;\n        levelSum += node.val;\n        if (node.left != null) {\n            queue.add(node.left);\n        }\n        if (node.right != null) {\n            queue.add(node.right);\n        }\n    }\n    if (levelSum >= bestSum) {\n        bestSum = levelSum;\n        bestLevel = level;\n    }\n    level++;\n}\nreturn bestLevel;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":11,"13":12,"14":13,"15":14,"16":15,"17":16,"18":18,"19":19,"20":22,"21":23,"22":24,"23":26,"24":28},"statementBundles":{"17":{"startLine":16,"endLine":17},"19":{"startLine":19,"endLine":21},"22":{"startLine":24,"endLine":25},"23":{"startLine":26,"endLine":27}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","ctaLabel":"Check edge cases","workspacePanel":"visualizer","body":["The sweep finishes one row's sum at a time and only moves the best level on a strictly larger total, so the earliest of any tie keeps the lead.","Now push on the inputs. One stresses the comparison itself: a tree where every value is negative, so the largest row sum is still below zero."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"tree":[-5,-6,-7],"swapped":[0,1,2]}}]}},{"id":"edge-negative","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What goes wrong if the best sum starts at 0?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-neg-state","state":{"tree":[-5,-6,-7],"node":0,"visited":[0]}}]},"summary":"Take the tree with root -5 and children -6 and -7, with the best sum seeded at 0.","options":[{"id":"no-level-wins","label":"No row ever beats 0, so the best level never moves off its placeholder","rationale":"Row 1 sums to -5 and row 2 to -13, both below the seed of 0. Neither passes a strictly-greater check against 0, so the best level stays at its placeholder. Seed the best sum below any possible level sum instead.","isCorrect":true},{"id":"reports-row1-fine","label":"It still reports level 1, the real winner","rationale":"Only by luck of the initial best_level value. The comparison against 0 fails for every row, so nothing is chosen on its merits; on a tree whose first negative row is not the answer, the placeholder is simply wrong.","isCorrect":false},{"id":"zero-is-a-level","label":"It reports a level whose sum is 0","rationale":"No row here sums to 0, so 0 is not a real level total. The seed of 0 is a phantom value that no level can beat, which is exactly the bug.","isCorrect":false}],"answer":"A best sum of 0 beats every row when all sums are negative, so no real row is ever chosen. Start the best sum below any possible level sum so the first row always takes the lead."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"From rule to code","title":"Turn the rule into code","ctaLabel":"Start coding","workspacePanel":"visualizer","summary":"Two details carry the correctness: move the best level only on a strictly larger sum, and start the best sum below every possible total.","body":["Seed a queue with the root and start the level counter at 1. Sweep while the queue holds nodes. Each pass: save the current width, start a fresh level sum, add up exactly that many nodes while enqueueing their children, then take that row's level over the best so far only if its sum is strictly larger.","The queue begins with just the root, the first row about to be swept."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"tree":[1,7,0,7,-8],"node":0}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the level-sum sweep","eyebrow":"Code the rule","summary":"You finish one row's total before the next row mixes in. Now build it: seed the queue with the root, loop while it holds nodes, snapshot the row width before each pass, sum exactly that many nodes while enqueueing their children, then return the level whose total came out largest.","workspacePanel":"code","checkpoints":[{"id":"init-structures","title":"Seed the BFS queue","description":"Create the traversal queue and initialize the best-level tracking state.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_bfs_result_and_queue","scope":"init-structures","readMode":"tree-value-query-v1"}]},"commonMistakes":["Forgetting to enqueue the root","Starting the level counter at zero"],"hint":"Start with one frontier containing the root and set the current level to 1.","semanticSpec":{"intent":"Initialize the BFS frontier and the state that will remember the best level.","doneWhen":"A queue-like frontier is seeded with the root and answer-tracking state is initialized before traversal.","shouldFailWhen":"The root is never inserted into a queue-like frontier or there is no best-level state.","roles":["root node","BFS queue","current level","best level"],"mustProve":["The root node is inserted into a queue-like frontier.","The solution initializes state for the current level and the best answer."],"mustNotAccept":["Traversing from an empty queue.","Only storing a level sum without any answer level."],"equivalentVariants":["Use a list-backed queue with a head index.","Use a deque seeded with the root."],"proofSnippets":[{"id":"py-max-level-sum-init","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]"}]}},{"id":"while-loop","title":"Loop while the frontier has nodes","description":"Continue processing levels until the queue frontier is exhausted.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"loops_while_bfs_frontier_non_empty","scope":"while-loop","readMode":"tree-value-query-v1"}]},"commonMistakes":["Using a single pass instead of a frontier loop","Stopping before all queued children are processed"],"hint":"The outer loop should be driven by whether unprocessed queue entries remain.","semanticSpec":{"intent":"Drive traversal from the BFS frontier until every enqueued tree node has been processed.","doneWhen":"The outer loop continues while the queue has unprocessed nodes.","shouldFailWhen":"The code processes only the root or uses a loop unrelated to the queue frontier.","roles":["BFS queue","head cursor","frontier loop"],"mustProve":["The traversal loop is controlled by the queue frontier.","The loop can continue after child nodes are enqueued."],"mustNotAccept":["Only one level is processed.","A loop bound that ignores newly enqueued children."],"equivalentVariants":["Use `while head < len(queue)` for a list-backed queue.","Use `while queue` for a deque."],"proofSnippets":[{"id":"py-max-level-sum-while-loop","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]\n        head = 0\n        best_level = 1\n        while head < len(queue):\n            node = queue[head]\n            head += 1\n            if node.left:\n                queue.append(node.left)\n            if node.right:\n                queue.append(node.right)\n        return best_level"}]}},{"id":"level-size","title":"Capture the level size","description":"Freeze the number of nodes in the current level before enqueueing children.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"captures_bfs_level_boundary","scope":"level-size","readMode":"tree-value-query-v1"}]},"commonMistakes":["Using the changing queue length inside the inner loop","Mixing current-level and next-level nodes in the same sum"],"hint":"Store the current frontier width before the inner loop starts.","semanticSpec":{"intent":"Separate the current level from children that will belong to the next level.","doneWhen":"The current queue width is captured at the start of each level iteration.","shouldFailWhen":"The inner loop is allowed to grow as children are appended.","roles":["BFS queue","level size","frontier boundary"],"mustProve":["The outer loop is queue-driven.","The current level width is stored before processing level nodes."],"mustNotAccept":["No stable boundary between current and next level.","Using the live queue length as the inner-loop bound."],"equivalentVariants":["Store `len(queue) - head` for a list-backed queue.","Store `len(queue)` before dequeuing a deque level."],"proofSnippets":[{"id":"py-max-level-sum-capture-size","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            level_size = len(queue) - head\n            for _ in range(level_size):\n                node = queue[head]\n                head += 1\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            break\n        return 1"}]}},{"id":"process-level","title":"Accumulate the level sum","description":"Consume the captured number of nodes, add their values into the current level sum, and enqueue their children for later levels.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"updates_level_aggregate_from_node_value","scope":"update-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Forgetting to add every node value","Processing children in the same level where they are discovered","Forgetting to enqueue children"],"hint":"The inner loop is bounded by the captured level size, and children are appended for future levels.","semanticSpec":{"intent":"Accumulate the current level's node values while preparing the next frontier.","doneWhen":"A bounded inner loop adds processed node values into the level sum and appends child links to the queue.","shouldFailWhen":"The code skips value accumulation, never enqueues children, or lets the inner loop grow with the queue.","roles":["level nodes","level sum","aggregate update","child frontier"],"mustProve":["The inner loop is bounded by the captured level size.","Each processed node contributes to the level sum.","Child links are enqueued for later levels."],"mustNotAccept":["Accumulating without a stable level boundary.","Processing without enqueueing children.","Enqueueing children without advancing through current nodes."],"equivalentVariants":["Use a head-index queue.","Use dequeue operations from a FIFO queue."],"proofSnippets":[{"id":"py-max-level-sum-process-level","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]\n        head = 0\n        result = []\n        while head < len(queue):\n            level_size = len(queue) - head\n            level_sum = 0\n            for _ in range(level_size):\n                node = queue[head]\n                head += 1\n                level_sum += node.val\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            result.append(level_sum)\n            break"}]}},{"id":"return-best-level","title":"Return the best level","description":"Return the level number whose completed level sum was largest.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_level_aggregate_result","scope":"return-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning the maximum sum instead of its level","Returning the current level after it has advanced past the answer"],"hint":"Return the stored level number for the largest completed sum.","semanticSpec":{"intent":"Return the answer state produced by the completed level aggregate comparisons.","doneWhen":"The terminal return uses the best-level state updated after processing each level.","shouldFailWhen":"The function returns the queue, current level counter, or best sum instead of the stored answer level.","roles":["best level","best sum","terminal return"],"mustProve":["The best-level state is updated from completed level sums.","The terminal return reads the best-level answer."],"mustNotAccept":["Returning the maximum level sum.","Returning the current loop counter after traversal.","Returning the active queue."],"equivalentVariants":["Return a scalar `best_level`.","Return the level field from a best-answer pair."],"proofSnippets":[{"id":"py-max-level-sum-return-best","language":"python","code":"class Solution:\n    def maxLevelSum(self, root):\n        queue = [root]\n        head = 0\n        level = 1\n        best_level = 1\n        best_sum = -10**18\n        while head < len(queue):\n            level_size = len(queue) - head\n            level_sum = 0\n            for _ in range(level_size):\n                node = queue[head]\n                head += 1\n                level_sum += node.val\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            if level_sum > best_sum:\n                best_sum = level_sum\n                best_level = level\n            level += 1\n        return best_level"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Carry it forward","summary":"You swept the tree row by row, summed each row, and tracked the level whose total was largest.","workspacePanel":"code","body":["Maximum level sum is breadth-first search plus one rule: total each row, and keep the level number behind the largest total. The row boundary, saved from the frontier width before the pass, keeps one row's nodes from leaking into the next. It runs in O(n) time, since each node is read once, and O(n) space for the widest row in the queue. The same sweep powers level order, level averages, and the largest value per row."],"takeaways":[{"title":"Carry the winning level","body":"The answer is a row number, so carry the best level alongside the best sum. On the tree, row 2 sums to 7 and wins, so return level 2."},{"title":"Move the best only on a strictly larger sum","body":"Use a strict greater-than so a later tied row cannot steal the lead. Rows 1 and 2 of [5, 2, 3] both sum to 5, and the answer is the smaller level, 1."},{"title":"Seed the best sum below every value","body":"Start the best sum lower than any row could total, so an all-negative tree like -5 over -6 and -7 still picks a real row instead of an unbeaten placeholder of 0."}],"nextAction":"Submit your solution to run it against every test case."}],"slidesOrigin":"authored"},"complexity":{"time":"O(n)","space":"O(n)","explanation":"Each tree node is enqueued and processed once. The queue can hold a full level of the tree, which is O(n) in the worst case."}}
