{"id":"find-largest-value-in-each-tree-row","title":"Find Largest Value in Each Tree Row","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 largest value in each row from top to bottom.\n\nEach answer entry should be computed from exactly the nodes that belong to that depth.","examples":[{"input":"root = {\"val\": 1, \"left\": {\"val\": 3, \"left\": {\"val\": 5}, \"right\": {\"val\": 3}}, \"right\": {\"val\": 2, \"right\": {\"val\": 9}}}","output":"[1, 3, 9]","explanation":"The largest values by level are 1, then max(3, 2) = 3, then max(5, 3, 9) = 9."},{"input":"root = {\"val\": -10, \"left\": {\"val\": -20}, \"right\": {\"val\": -3}}","output":"[-10, -3]","explanation":"The second row contains -20 and -3, so the largest value is -3."},{"input":"root = null","output":"[]","explanation":"An empty tree has no rows."}],"constraints":[{"id":"the-number-of-nodes-in-the-tree-is-in-the-range-0-10000","text":"The number of nodes in the tree is in the range [0, 10000].","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":0,"max":10000}},{"id":"2147483648-node-val-2147483647","text":"-2147483648 <= Node.val <= 2147483647","check":{"kind":"valueRange","target":"root","selector":"treeValues","min":-2147483648,"max":2147483647}}],"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 largestValues(self, root: TreeNode) -> list[int]:\n        # Your code here\n        pass","functionName":"largestValues","testCases":[{"id":"1","input":{"root":{"val":1,"left":{"val":3,"left":{"val":5,"left":null,"right":null,"__id__":"tree-3"},"right":{"val":3,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-1"},"right":{"val":2,"left":null,"right":{"val":9,"left":null,"right":null,"__id__":"tree-5"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[1,3,9],"description":"Canonical tree with three rows."},{"id":"2","input":{"root":{"val":-10,"left":{"val":-20,"left":null,"right":null,"__id__":"tree-1"},"right":{"val":-3,"left":null,"right":null,"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[-10,-3],"description":"Negative values still use the maximum value, not the largest absolute value."},{"id":"3","input":{"root":{"val":7,"left":null,"right":null,"__id__":"tree-0"}},"expected":[7],"description":"Single node tree."},{"id":"4","input":{"root":{"val":5,"left":{"val":4,"left":{"val":3,"left":null,"right":null,"__id__":"tree-2"},"right":null,"__id__":"tree-1"},"right":null,"__id__":"tree-0"}},"expected":[5,4,3],"description":"Left-skewed tree has one value per row."},{"id":"5","input":{"root":{"val":0,"left":{"val":-1,"left":{"val":-5,"left":null,"right":null,"__id__":"tree-3"},"right":null,"__id__":"tree-1"},"right":{"val":6,"left":{"val":4,"left":null,"right":null,"__id__":"tree-4"},"right":{"val":10,"left":null,"right":null,"__id__":"tree-5"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[0,6,10],"description":"Mixed shape where the largest row value can be on either side."},{"id":"h1","input":{"root":null},"expected":[],"description":"Empty tree."},{"id":"h2","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":null,"right":null,"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[-1,-2,-4],"description":"All values are negative."},{"id":"h3","input":{"root":{"val":0,"left":{"val":-2147483648,"left":null,"right":null,"__id__":"tree-1"},"right":{"val":2147483647,"left":{"val":-2147483648,"left":null,"right":null,"__id__":"tree-3"},"right":null,"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[0,2147483647,-2147483648],"description":"Integer boundary values."},{"id":"h4","input":{"root":{"val":0,"left":{"val":-1,"left":{"val":2,"left":null,"right":null,"__id__":"tree-7"},"right":null,"__id__":"tree-6"},"right":{"val":-3,"left":null,"right":{"val":4,"left":null,"right":null,"__id__":"tree-9"},"__id__":"tree-8"},"__id__":"tree-5"}},"expected":[0,-1,4],"description":"A deeper right-side value can win a lower row."},{"id":"h5","input":{"root":{"val":7,"left":{"val":1,"left":null,"right":{"val":8,"left":null,"right":null,"__id__":"tree-12"},"__id__":"tree-11"},"right":{"val":6,"left":{"val":9,"left":null,"right":null,"__id__":"tree-14"},"right":null,"__id__":"tree-13"},"__id__":"tree-10"}},"expected":[7,6,9],"description":"The row maximum can move from left to right across levels."},{"id":"topup-1","input":{"root":{"val":2,"left":{"val":1,"left":null,"right":{"val":7,"left":null,"right":null,"__id__":"tree-topup-3"},"__id__":"tree-topup-1"},"right":{"val":3,"left":{"val":6,"left":null,"right":null,"__id__":"tree-topup-4"},"right":{"val":5,"left":null,"right":null,"__id__":"tree-topup-5"},"__id__":"tree-topup-2"},"__id__":"tree-topup-0"}},"expected":[2,3,7],"description":"Top-up case 1: a lower-level maximum can come from a non-leftmost grandchild."},{"id":"topup-2","input":{"root":{"val":-4,"left":null,"right":{"val":-2,"left":{"val":-9,"left":null,"right":null,"__id__":"tree-topup-8"},"right":{"val":-3,"left":null,"right":null,"__id__":"tree-topup-9"},"__id__":"tree-topup-7"},"__id__":"tree-topup-6"}},"expected":[-4,-2,-3],"description":"Top-up case 2: sparse right-heavy negative rows still choose the numerically largest value."}],"hints":[{"level":1,"content":"Each output value belongs to one tree row, so keep the current row separate from the next row.","revealPattern":false},{"level":2,"content":"Use a queue and capture the queue size before processing each row.","revealPattern":true},{"level":3,"content":"Reset a row maximum before each row, update it while consuming exactly row_size nodes, then append it.","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-maximum","name":"BFS row frontier","summary":"Hold one row in a queue, take that row’s maximum, then enqueue its children as the next row and repeat.","decisionReason":"A queue gathers each depth into one frontier, and snapshotting the frontier’s width marks where the row ends, so the maximum of exactly that row falls out in one pass.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space for the widest row."],"isOptimal":true,"steps":["Seed a queue with the root.","Snapshot the current frontier width before processing it.","Take the maximum over exactly those nodes, then enqueue their children."]},{"id":"dfs-depth-buckets","name":"DFS with depth buckets","summary":"Recurse through the tree carrying each node’s depth, and keep a running maximum per depth in a list indexed by depth.","decisionReason":"Depth-indexed DFS finds the same maximum for every row in O(n) time. The trace uses a queue so each row and its running maximum stay visible as one frontier.","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."],"isViable":true,"isOptimal":false,"steps":["Visit each node carrying its depth.","Update the stored maximum for that depth.","Read the depth list out in order after the traversal."]}]},"codingCheckpoints":[{"id":"check-empty","title":"Handle the empty tree","description":"Return an empty list when there is no root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"handles_empty_tree_return","scope":"check-empty","readMode":"tree-value-query-v1"}]},"commonMistakes":["Trying to enqueue a null root","Returning null instead of an empty list"],"hint":"Short-circuit before any queue setup.","semanticSpec":{"intent":"Handle the empty-tree boundary case before starting BFS.","doneWhen":"The function checks for a missing root and returns an empty list.","shouldFailWhen":"The code enqueues a missing root or returns a non-list placeholder.","roles":["root node","empty result"],"mustProve":["A missing root is checked before traversal setup.","The empty tree returns an empty list."],"mustNotAccept":["Queue setup before the empty-tree guard.","Returning null for an empty tree."],"equivalentVariants":["Use a falsy root check.","Use an explicit null check."],"proofSnippets":[{"id":"py-largest-row-empty-tree-return","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []"}]}},{"id":"init-structures","title":"Seed the BFS queue","description":"Create the result list and seed the traversal queue with the root node.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_bfs_result_and_queue","scope":"init-structures","readMode":"tree-value-query-v1"}]},"commonMistakes":["Creating a result list but never adding the root to the queue","Using a stack-style traversal"],"hint":"Start with one frontier containing only the root.","semanticSpec":{"intent":"Initialize the output collection and BFS frontier from the root.","doneWhen":"A result list exists and a queue-like frontier is seeded with the root.","shouldFailWhen":"The queue is never seeded with the root or the result collection is missing.","roles":["result list","BFS queue","root node"],"mustProve":["A result collection is initialized.","The root node is inserted into a queue-like frontier."],"mustNotAccept":["Creating a queue without the root.","Using a stack-style setup."],"equivalentVariants":["Use a list-backed queue with a head index.","Use a deque seeded with the root."],"proofSnippets":[{"id":"py-largest-row-init-result-and-queue","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]"}]}},{"id":"level-size","title":"Capture the row size","description":"Store the number of nodes currently in the frontier 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-row and next-row nodes in one maximum"],"hint":"Freeze the current frontier width at the start of each row.","semanticSpec":{"intent":"Capture the current frontier width before child nodes can extend the queue.","doneWhen":"The row size is stored at the start of a queue-driven row iteration.","shouldFailWhen":"The code reads the changing queue length while processing the row.","roles":["BFS queue","row size","frontier boundary"],"mustProve":["The traversal loop is driven by the queue frontier.","The current row width is captured before processing row nodes."],"mustNotAccept":["No stable boundary between current and next row.","Using the changing queue length as the inner-loop bound."],"equivalentVariants":["Store len(queue) - head before the row loop.","Store the current deque length before popping row nodes."],"proofSnippets":[{"id":"py-largest-row-capture-row-size","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            break\n        return result"}]}},{"id":"reset-aggregate","title":"Reset the row maximum","description":"Start each row with a fresh maximum before processing its nodes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"resets_level_aggregate_state","scope":"reset-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Letting the previous row's maximum carry into the next row","Resetting the maximum inside the inner loop"],"hint":"The row maximum should reset once per row.","semanticSpec":{"intent":"Start each row with a fresh aggregate state for that row's maximum.","doneWhen":"A row maximum is initialized inside the outer row loop before row nodes are processed.","shouldFailWhen":"The maximum carries over from a previous row or is reset for every node.","roles":["row maximum","row loop","aggregate state"],"mustProve":["The aggregate state is reset once per row.","The reset happens before the row's node-processing loop."],"mustNotAccept":["One global maximum shared by all rows.","Resetting the row maximum inside the node loop."],"equivalentVariants":["Initialize the row maximum to the minimum integer value.","Initialize the row maximum from the first value in the captured row."],"proofSnippets":[{"id":"py-largest-row-reset-row-maximum","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            row_max = -2147483648\n            for _ in range(row_size):\n                node = queue[head]\n                head += 1\n                row_max = max(row_max, node.val)\n            break\n        return result"}]}},{"id":"process-level","title":"Process exactly this row","description":"Consume exactly the captured number of nodes, update the row maximum, and enqueue children for later rows.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"processes_level_order_aggregate_nodes","scope":"process-level","readMode":"tree-value-query-v1"}]},"commonMistakes":["Forgetting to compare each node value","Processing nodes added for the next row too early","Forgetting to enqueue children"],"hint":"The inner loop should be bounded by the captured row size.","semanticSpec":{"intent":"Consume exactly the captured row, update the row maximum from node values, and enqueue children for later rows.","doneWhen":"A bounded inner loop advances through row nodes, compares each value into the row maximum, and appends children to the frontier.","shouldFailWhen":"The loop skips the value comparison, consumes next-row nodes early, or never enqueues children.","roles":["row nodes","row maximum","child frontier"],"mustProve":["The inner loop is bounded by the captured row size.","Each processed node can update the row maximum.","Child links are enqueued for later rows."],"mustNotAccept":["Processing without updating the maximum.","Processing without enqueueing children.","Using a loop bound that grows as children are added."],"equivalentVariants":["Use a head-index queue.","Use dequeue operations from a FIFO queue."],"proofSnippets":[{"id":"py-largest-row-process-captured-row","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            row_max = -2147483648\n            for _ in range(row_size):\n                node = queue[head]\n                head += 1\n                row_max = max(row_max, node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            break\n        return result"}]}},{"id":"emit-largest","title":"Append the row maximum","description":"After the row is processed, append the maximum found for that row.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"emits_level_aggregate_outcome","scope":"emit-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Appending before every node has been processed","Appending the node value without comparing against the row maximum"],"hint":"Append one value after the inner loop finishes.","semanticSpec":{"intent":"Emit one aggregate outcome for the completed row.","doneWhen":"The row maximum is appended after the row's bounded node loop finishes.","shouldFailWhen":"The code appends before the row is complete or appends a raw node value without the aggregate.","roles":["row maximum","result list","completed row"],"mustProve":["The row maximum is updated from row node values.","One row maximum is appended after row processing."],"mustNotAccept":["Appending once per node.","Appending before comparing all nodes in the row."],"equivalentVariants":["Append the row maximum to the result list.","Push the row maximum into the output collection."],"proofSnippets":[{"id":"py-largest-row-emit-row-maximum","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            row_max = -2147483648\n            for _ in range(row_size):\n                node = queue[head]\n                head += 1\n                row_max = max(row_max, node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            result.append(row_max)\n            break"}]}},{"id":"return-values","title":"Return all row maximums","description":"Return the collected row maximums after every row has been processed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_level_aggregate_result","scope":"return-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning only the last row maximum","Returning the queue instead of the result"],"hint":"Return the result list after the BFS loop completes.","semanticSpec":{"intent":"Return the completed list of row maximums after BFS finishes.","doneWhen":"The terminal return uses the result collection populated by the row aggregate loop.","shouldFailWhen":"The function returns only the last maximum, the queue, or no value.","roles":["result list","row maximums","terminal return"],"mustProve":["The result collection receives row maximums.","The terminal return reads that result collection."],"mustNotAccept":["Returning the active queue.","Returning the last row maximum scalar.","No terminal return of the aggregate output."],"equivalentVariants":["Return the result list directly.","Return an alias that stores the row maximum output."],"proofSnippets":[{"id":"py-largest-row-return-results","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            row_max = -2147483648\n            for _ in range(row_size):\n                node = queue[head]\n                head += 1\n                row_max = max(row_max, node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            result.append(row_max)\n        return result"}]}}],"slides":[{"id":"opener","chapter":"The task","kind":"info","eyebrow":"Read the problem","title":"One number per tree row","workspacePanel":"problem","body":["A binary tree stacks its nodes in rows by depth: the root is row one, its children are row two, their children are row three. For each row, return its largest value, top to bottom.","Every node belongs to exactly one row, and each row contributes exactly one number. The whole question is which nodes share a row."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"opener-state","state":{"tree":[3,1,5,9,2,null,4],"swapped":[2,3]}}]}},{"id":"rescan-rows","chapter":"The obvious way","kind":"code-trace","eyebrow":"Start with the naive way","title":"Bucket every node by its depth, then reduce","summary":"The answer is one number per depth, so the plainest version walks the tree once, dropping each node’s value into a list for its own depth. Once every node is filed away, scan each stored row and keep its largest.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def largestValues(root: TreeNode | None) -> list[int]:\n    if not root:\n        return []\n    rows = []\n    nodes = [root]\n    depths = [0]\n    while nodes:\n        node = nodes.pop()\n        depth = depths.pop()\n        if depth == len(rows):\n            rows.append([])\n        rows[depth].append(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    result = []\n    for row in rows:\n        row_max = -2147483648\n        for value in row:\n            row_max = max(row_max, value)\n        result.append(row_max)\n    return result","steps":[{"id":"rs-root","title":"File the root under depth 0","codeLine":12,"summary":"The walk reads 3 and drops it into the depth-0 list. rows now holds [[3]].","state":{"tree":[3,1,5,9,2,null,4],"node":0}},{"id":"rs-fill","title":"Every node lands in its depth’s list","codeLine":12,"summary":"The walk keeps going until 1 and 5 are filed under depth 1 and 9, 2, and 4 under depth 2. rows holds [[3], [1, 5], [9, 2, 4]], the whole tree stored row by row.","state":{"tree":[3,1,5,9,2,null,4],"visited":[0],"swapped":[1,2,3,4,6]}},{"id":"rs-reduce","title":"Only now, scan each stored row for its maximum","codeLine":23,"summary":"With every row already in memory, a second sweep takes the maximum of each: 3, then 5, then 9. result becomes [3, 5, 9].","state":{"tree":[3,1,5,9,2,null,4],"visited":[0,1,2],"swapped":[3,4,6]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (!root) {\n    return [];\n}\nconst rows = [];\nconst nodes = [root];\nconst depths = [0];\nwhile (nodes.length > 0) {\n    const node = nodes.pop();\n    const depth = depths.pop();\n    if (depth == rows.length) {\n        rows.push([]);\n    }\n    rows[depth].push(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}\nconst result = [];\nfor (const row of rows) {\n    let rowMax = -2147483648;\n    for (const value of row) {\n        rowMax = Math.max(rowMax, value);\n    }\n    result.push(rowMax);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":13,"13":14,"14":15,"15":16,"16":18,"17":19,"18":20,"19":23,"20":24,"21":25,"22":26,"23":27,"24":29,"25":31},"statementBundles":{"3":{"startLine":2,"endLine":3},"11":{"startLine":11,"endLine":12},"15":{"startLine":16,"endLine":17},"18":{"startLine":20,"endLine":22},"23":{"startLine":27,"endLine":28},"24":{"startLine":29,"endLine":30}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (!root) {\n    return [];\n}\nconst rows: Array<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 == rows.length) {\n        rows.push([]);\n    }\n    rows[depth].push(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}\nconst result: Array<number> = [];\nfor (const row of rows) {\n    let rowMax = -2147483648;\n    for (const value of row) {\n        rowMax = Math.max(rowMax, value);\n    }\n    result.push(rowMax);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":13,"13":14,"14":15,"15":16,"16":18,"17":19,"18":20,"19":23,"20":24,"21":25,"22":26,"23":27,"24":29,"25":31},"statementBundles":{"3":{"startLine":2,"endLine":3},"11":{"startLine":11,"endLine":12},"15":{"startLine":16,"endLine":17},"18":{"startLine":20,"endLine":22},"23":{"startLine":27,"endLine":28},"24":{"startLine":29,"endLine":30}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (root == null) {\n    return new List<int>();\n}\nList<List<int>> rows = 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 == rows.Count) {\n        rows.Add(new List<int>());\n    }\n    rows[depth].Add(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}\nList<int> result = new();\nforeach (var row in rows) {\n    int rowMax = -2147483648;\n    foreach (int value in row) {\n        rowMax = Math.Max(rowMax, value);\n    }\n    result.Add(rowMax);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":12,"11":13,"12":15,"13":16,"14":17,"15":18,"16":20,"17":21,"18":22,"19":25,"20":26,"21":27,"22":28,"23":29,"24":31,"25":33},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":9},"9":{"startLine":10,"endLine":11},"11":{"startLine":13,"endLine":14},"15":{"startLine":18,"endLine":19},"18":{"startLine":22,"endLine":24},"23":{"startLine":29,"endLine":30},"24":{"startLine":31,"endLine":32}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (!root) {\n    return vector<int>{};\n}\nvector<vector<int>> rows;\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 == rows.size()) {\n        rows.push_back(vector<int>{});\n    }\n    rows[depth].push_back(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}\nvector<int> result;\nfor (vector<int> row : rows) {\n    int row_max = -2147483648;\n    for (int value : row) {\n        row_max = max(row_max, value);\n    }\n    result.push_back(row_max);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":12,"11":13,"12":15,"13":16,"14":17,"15":18,"16":20,"17":21,"18":22,"19":25,"20":26,"21":27,"22":28,"23":29,"24":31,"25":33},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":9},"9":{"startLine":10,"endLine":11},"11":{"startLine":13,"endLine":14},"15":{"startLine":18,"endLine":19},"18":{"startLine":22,"endLine":24},"23":{"startLine":29,"endLine":30},"24":{"startLine":31,"endLine":32}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (root == null) {\n    return new ArrayList<>();\n}\nList<List<Integer>> rows = 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 == rows.size()) {\n        rows.add(new ArrayList<>());\n    }\n    rows.get(depth).add(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}\nList<Integer> result = new ArrayList<>();\nfor (List<Integer> row : rows) {\n    int rowMax = -2147483648;\n    for (Integer value : row) {\n        rowMax = Math.max(rowMax, value);\n    }\n    result.add(rowMax);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":13,"13":14,"14":15,"15":16,"16":18,"17":19,"18":20,"19":23,"20":24,"21":25,"22":26,"23":27,"24":29,"25":31},"statementBundles":{"3":{"startLine":2,"endLine":3},"11":{"startLine":11,"endLine":12},"15":{"startLine":16,"endLine":17},"18":{"startLine":20,"endLine":22},"23":{"startLine":27,"endLine":28},"24":{"startLine":29,"endLine":30}}}}}},{"id":"rescan-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Count the cost","title":"How much of the tree is held in memory at once?","workspacePanel":"visualizer","summary":"The baseline runs in two phases: first the walk buckets every node into a list for its own depth, then a second loop reduces each stored row to its maximum.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rescan-cost-state","state":{"tree":[3,1,5,9,2,null,4],"swapped":[0,1,2,3,4,6]}}]},"options":[{"id":"cost-all-rows","label":"Every node of every row, since the reduce only starts after the whole tree is filed","rationale":"Each maximum is computed in the second loop, which runs only after the walk has bucketed all n nodes. So every row stays alive in rows at once, even though each row’s answer is a single number.","isCorrect":true},{"id":"cost-one-row","label":"Only the widest single row, the rest is discarded as it goes","rationale":"This naive never drops a row mid-walk. Nothing reduces a depth until every depth is collected, so all the rows stay live together rather than one at a time.","isCorrect":false},{"id":"cost-one-number","label":"Just the running maximum, one number","rationale":"A running maximum is the right shape, but this version computes no maximum until the walk ends. Until then it keeps every value.","isCorrect":false}],"answer":"Reducing only after the full walk keeps every row live in rows at once. The answer needs only one number per row, so each row has to stay live just long enough to take its maximum: take a row’s max as soon as that row is gathered, and no row needs to outlive the row below it."},{"id":"follow-max","chapter":"A one-pass shortcut","kind":"code-trace","eyebrow":"Watch a tempting fix","title":"Could one descending path replace the re-walks?","summary":"To kill the re-walks, a tempting one-pass shortcut keeps only the current row winner, looks at its children, and lets the largest child carry the next row. One node tracked straight down, recorded at each depth.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def largestValues(root: TreeNode | None) -> list[int]:\n    result = []\n    best = root\n    while best:\n        result.append(best.val)\n        children = []\n        if best.left:\n            children.append(best.left)\n        if best.right:\n            children.append(best.right)\n        nxt = None\n        for child in children:\n            if nxt is None or child.val > nxt.val:\n                nxt = child\n        best = nxt\n    return result","steps":[{"id":"fm-root","title":"Row one is the root","codeLine":5,"summary":"On the tree, row one holds only 3, so record 3. result is [3].","state":{"tree":[3,1,5,9,2,null,4],"node":0}},{"id":"fm-pick-5","title":"Among the root’s children, 5 is larger","codeLine":14,"summary":"The children of 3 are 1 and 5. The guess keeps the larger one, 5, as the next winner. On the next pass it records 5, so result is [3, 5].","state":{"tree":[3,1,5,9,2,null,4],"node":2,"visited":[0],"swapped":[1,2]}},{"id":"fm-descend-5","title":"Only 5’s own child survives","codeLine":5,"summary":"The guess now descends from 5 alone. Its only child is 4, so row three as it sees it is just 4, and it records 4. result becomes [3, 5, 4].","state":{"tree":[3,1,5,9,2,null,4],"node":6,"visited":[0,2],"swapped":[6]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nlet best = root;\nwhile (best != null) {\n    result.push(best.val);\n    const children = [];\n    if (best.left) {\n        children.push(best.left);\n    }\n    if (best.right) {\n        children.push(best.right);\n    }\n    let nxt = null;\n    for (const child of children) {\n        if (nxt === null || child.val > nxt.val) {\n            nxt = child;\n        }\n    }\n    best = nxt;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":12,"12":13,"13":14,"14":15,"15":18,"16":20},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11},"14":{"startLine":15,"endLine":17},"15":{"startLine":18,"endLine":19}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<number> = [];\nlet best = root;\nwhile (best != null) {\n    result.push(best.val);\n    const children: Array<TreeNode | null> = [];\n    if (best.left) {\n        children.push(best.left);\n    }\n    if (best.right) {\n        children.push(best.right);\n    }\n    let nxt = null;\n    for (const child of children) {\n        if (nxt === null || child.val > nxt.val) {\n            nxt = child;\n        }\n    }\n    best = nxt;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":12,"12":13,"13":14,"14":15,"15":18,"16":20},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11},"14":{"startLine":15,"endLine":17},"15":{"startLine":18,"endLine":19}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> result = new();\nTreeNode best = root;\nwhile (best != null) {\n    result.Add(best.val);\n    List<TreeNode> children = new();\n    if (best.left != null) {\n        children.Add(best.left);\n    }\n    if (best.right != null) {\n        children.Add(best.right);\n    }\n    TreeNode nxt = null;\n    foreach (var child in children) {\n        if (nxt == null || child.val > nxt.val) {\n            nxt = child;\n        }\n    }\n    best = nxt;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":12,"12":13,"13":14,"14":15,"15":18,"16":20},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11},"14":{"startLine":15,"endLine":17},"15":{"startLine":18,"endLine":19}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> result;\nTreeNode* best = root;\nwhile (best) {\n    result.push_back(best->val);\n    vector<TreeNode*> children;\n    if (best->left) {\n        children.push_back(best->left);\n    }\n    if (best->right) {\n        children.push_back(best->right);\n    }\n    TreeNode* nxt = nullptr;\n    for (TreeNode* child : children) {\n        if ((nxt == nullptr || child->val > nxt->val)) {\n            nxt = child;\n        }\n    }\n    best = nxt;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":12,"12":13,"13":14,"14":15,"15":18,"16":20},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11},"14":{"startLine":15,"endLine":17},"15":{"startLine":18,"endLine":19}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> result = new ArrayList<>();\nTreeNode best = root;\nwhile (best != null) {\n    result.add(best.val);\n    List<TreeNode> children = new ArrayList<>();\n    if (best.left != null) {\n        children.add(best.left);\n    }\n    if (best.right != null) {\n        children.add(best.right);\n    }\n    TreeNode nxt = null;\n    for (TreeNode child : children) {\n        if (nxt == null || child.val > nxt.val) {\n            nxt = child;\n        }\n    }\n    best = nxt;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":12,"12":13,"13":14,"14":15,"15":18,"16":20},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11},"14":{"startLine":15,"endLine":17},"15":{"startLine":18,"endLine":19}}}}}},{"id":"follow-max-fails","chapter":"A one-pass shortcut","kind":"case-probe","eyebrow":"Force a decision","title":"Why did chasing the biggest node report 4 for the third row?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fmf-state","state":{"tree":[3,1,5,9,2,null,4],"node":6,"visited":[0,2],"swapped":[3,4]}}]},"summary":"The trace returned [3, 5, 4], but the third row is 9, 2, and 4.","options":[{"id":"all-nodes-count","label":"A row’s largest can sit under a smaller node, so every node at the depth must be weighed","rationale":"The 9 is a child of 1, the smaller node in row two. Throwing 1 away threw 9 away with it. The third row’s largest is 9, but it lives under the node the chase discarded.","isCorrect":true},{"id":"compare-bug","label":"The comparison picked the wrong child of 5","rationale":"The comparison was right: 4 is the larger of 5’s children. The flaw is looking only under 5. The winning 9 descends from 1, which was never expanded.","isCorrect":false},{"id":"start-left","label":"It should have chased the smaller node, 1, instead","rationale":"Chasing 1 would have found 9 but lost 4, and on another tree the winner switches sides again. No single descending path sees every node of a row.","isCorrect":false}],"answer":"A row’s largest can descend from any node above it, so each row’s answer must consider all nodes at that depth, including nodes below smaller parents."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","title":"Which traversal makes a row boundary cheap to know?","eyebrow":"Pick the route","summary":"Taking the maximum of a depth needs that depth’s nodes settled together before the next depth mixes in. The two traversals differ in how easily they mark where one row ends.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"tree":[3,1,5,9,2,null,4]}}]},"selection":{"contract":"approach-selection-v1","question":"Now let’s compare possible approaches. Which one should we use?","decisionPrompt":"Both are O(n) and correct, so neither wins on complexity. This lesson practices reading a row boundary directly, so pick the traversal whose state already holds one depth together as a frontier you can snapshot.","approaches":[{"id":"bfs-level-maximum","name":"Queue by arrival order","summary":"Process nodes in the order they were reached, oldest first, adding each node’s children to the back of the line.","decisionReason":"This is what the lesson practices: reaching nodes oldest-first means a whole depth sits in the queue together before any of its children arrive, so one row appears as a frontier you can snapshot and the row boundary falls out of its width. It does not beat DFS on complexity; it just makes the row boundary the thing you hold.","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.","Snapshot the current frontier width before processing it.","Take the maximum over exactly those nodes, then enqueue their children."]},{"id":"dfs-depth-buckets","name":"Depth-indexed recursion","summary":"Recurse through the tree carrying each node’s depth, and keep a running maximum per depth in a list indexed by depth.","decisionReason":"Depth-indexed DFS finds the same maximum for every row in O(n) time. The trace uses a queue so each row and its running maximum stay visible as one frontier.","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.","Update the stored maximum for that depth.","Read the depth list out in order after the traversal."]}]}},{"id":"trace-setup","chapter":"Trace","kind":"info","eyebrow":"Set up the sweep","title":"Fan the tree out by depth 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 best for the row being read its row maximum.","On the tree, row two holds 1 and 5, and row three holds 9, 2, and 4. Predict the number each row hands to the answer."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"trace-setup-state","state":{"tree":[3,1,5,9,2,null,4],"node":0,"swapped":[1,2]}}]}},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the sweep","title":"Sweep three rows","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"beat-row1","state":{"tree":[3,1,5,9,2,null,4],"node":0,"visited":[0]}},{"id":"beat-row2-bound","state":{"tree":[3,1,5,9,2,null,4],"visited":[0],"swapped":[1,2]}},{"id":"beat-row2-max","state":{"tree":[3,1,5,9,2,null,4],"node":2,"visited":[0],"swapped":[1,2]}},{"id":"beat-row3-max","state":{"tree":[3,1,5,9,2,null,4],"node":3,"visited":[0,1,2],"swapped":[3,4,6]}}]},"beats":[{"id":"beat-row1","title":"Row one holds only the root. What does it contribute?","summary":"The queue holds just the root 3, so this row has one node.","options":[{"id":"r1-3","label":"Append 3, the only value in the row","rationale":"A single node is its own row maximum, so row one contributes 3. The answer starts as [3].","isCorrect":true},{"id":"r1-wait","label":"Wait until a row has more than one node","rationale":"Every row contributes one value, including a row of one. Row one’s maximum is 3.","isCorrect":false},{"id":"r1-both","label":"Append 3 and its children 1 and 5 together","rationale":"The children belong to the next row and the next pass. Only the current row’s nodes feed this maximum.","isCorrect":false}],"answer":"Row one has the single node 3, so it contributes 3 and the answer is [3]."},{"id":"beat-row2-bound","title":"Children pile up behind. How many nodes belong to row two?","summary":"Reading each waiting node enqueues its children right behind them, 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, 1 and 5, were queued at the start of the pass. Fix that count first, weigh 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 1 and 5 enter the queue during the pass. Draining it pulls 9, 2, and 4 into row two as well, merging two rows into one maximum.","isCorrect":false},{"id":"r2-one","label":"Just the first node, 1, then move on","rationale":"Stopping at 1 misses 5, the larger node still waiting in the same row. A row’s maximum needs every node at the depth.","isCorrect":false}],"answer":"Lock in the width, two, before the pass, so 9, 2, and 4 stay in row three even as they pile up behind."},{"id":"beat-row2-max","title":"What value does row two contribute?","summary":"Row two holds 1 and 5.","options":[{"id":"r2-five","label":"5, the larger of the two","rationale":"The row maximum compares 1 and 5 and keeps 5. The answer becomes [3, 5]. The right node has the larger value.","isCorrect":true},{"id":"r2-one-val","label":"1, the first node in the row","rationale":"Position does not decide it. 1 is reached first and 5 is larger, so the maximum is 5.","isCorrect":false},{"id":"r2-both-val","label":"Both 1 and 5","rationale":"Each row contributes one number, its maximum. Only 5 is kept here.","isCorrect":false}],"answer":"Row two’s maximum is 5, so the answer is [3, 5]."},{"id":"beat-row3-max","title":"What does the answer become after row three?","summary":"Row three holds 9 and 2 (children of 1) then 4 (child of 5).","options":[{"id":"r3-nine","label":"9 is appended, giving [3, 5, 9]","rationale":"The row maximum over 9, 2, and 4 is 9, the first node reached. The queue empties after, so the final answer is [3, 5, 9].","isCorrect":true},{"id":"r3-four","label":"4 is appended, giving [3, 5, 4]","rationale":"4 is reached last. The row maximum remains 9 because 9 is larger.","isCorrect":false},{"id":"r3-five-again","label":"Nothing new, the answer stays [3, 5]","rationale":"Row three still has nodes, so it contributes its maximum. The sweep ends only when the queue is empty.","isCorrect":false}],"answer":"9 is the largest in row three, so it is appended and the final answer is [3, 5, 9]."}]},{"id":"boundary-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could the inner loop just run while the queue still has unread nodes?","summary":"What if you skip the saved width and let the inner loop run while unread nodes remain, taking the maximum as you go? Every node is still visited once and the maximum still updates. Watch where it decides a row has ended.","workspacePanel":"trace","pitfall":"The loop below resets a row maximum, but its inner loop keeps consuming while unread nodes remain, instead of stopping at a width saved before the pass.","whyItMatters":"Save the frontier width before the pass and bound the inner loop by that count. Read the live width instead and the children enqueued mid-pass extend the same loop, so every node collapses into one row and the answer holds a single global maximum.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def largestValues(root: TreeNode | None) -> list[int]:\n    if not root:\n        return []\n    result = []\n    queue = [root]\n    head = 0\n    while head < len(queue):\n        row_max = -2147483648\n        while head < len(queue):\n            node = queue[head]\n            head += 1\n            row_max = max(row_max, node.val)\n            if node.left:\n                queue.append(node.left)\n            if node.right:\n                queue.append(node.right)\n        result.append(row_max)\n    return result","steps":[{"id":"pit-root","title":"Row one starts the maximum at the root","codeLine":12,"summary":"On the tree, the row maximum starts and the root 3 is read first. So far this matches a correct sweep.","state":{"tree":[3,1,5,9,2,null,4],"node":0,"visited":[0]}},{"id":"pit-enqueue","title":"Reading 3 enqueues its children behind it","codeLine":14,"summary":"Processing 3 appends 1 and 5 to the queue. The inner loop’s condition checks the live width, which now includes them.","state":{"tree":[3,1,5,9,2,null,4],"node":0,"visited":[0],"swapped":[1,2]}},{"id":"pit-eat-row2","title":"The same loop keeps going into row two","codeLine":9,"summary":"Because unread nodes remain, the inner loop does not stop. It reads 1 and 5 into the same maximum and enqueues 9, 2, and 4 behind them.","state":{"tree":[3,1,5,9,2,null,4],"node":2,"visited":[0,1,2],"swapped":[3,4,6]}},{"id":"pit-wrong","title":"Every row collapsed into one number","codeLine":18,"summary":"The loop never stopped until the whole tree was read, so one maximum, 9, was appended and the function returns [9] instead of [3, 5, 9].","state":{"tree":[3,1,5,9,2,null,4],"visited":[0,1,2,3,4,6],"swapped":[3]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (!root) {\n    return [];\n}\nconst result = [];\nconst queue = [root];\nlet head = 0;\nwhile (head < queue.length) {\n    let rowMax = -2147483648;\n    while (head < queue.length) {\n        const node = queue[head];\n        head++;\n        rowMax = Math.max(rowMax, node.val);\n        if (node.left) {\n            queue.push(node.left);\n        }\n        if (node.right) {\n            queue.push(node.right);\n        }\n    }\n    result.push(rowMax);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":16,"16":17,"17":20,"18":22},"statementBundles":{"3":{"startLine":2,"endLine":3},"14":{"startLine":14,"endLine":15},"16":{"startLine":17,"endLine":19},"17":{"startLine":20,"endLine":21}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (!root) {\n    return [];\n}\nconst result: Array<number> = [];\nconst queue = [root];\nlet head = 0;\nwhile (head < queue.length) {\n    let rowMax = -2147483648;\n    while (head < queue.length) {\n        const node = queue[head];\n        head++;\n        rowMax = Math.max(rowMax, node.val);\n        if (node.left) {\n            queue.push(node.left);\n        }\n        if (node.right) {\n            queue.push(node.right);\n        }\n    }\n    result.push(rowMax);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":16,"16":17,"17":20,"18":22},"statementBundles":{"3":{"startLine":2,"endLine":3},"14":{"startLine":14,"endLine":15},"16":{"startLine":17,"endLine":19},"17":{"startLine":20,"endLine":21}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (root == null) {\n    return new List<int>();\n}\nList<int> result = new();\nList<TreeNode> queue = new() { root };\nint head = 0;\nwhile (head < queue.Count) {\n    int rowMax = -2147483648;\n    while (head < queue.Count) {\n        TreeNode node = queue[head];\n        head++;\n        rowMax = Math.Max(rowMax, 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    result.Add(rowMax);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":16,"16":17,"17":20,"18":22},"statementBundles":{"3":{"startLine":2,"endLine":3},"14":{"startLine":14,"endLine":15},"16":{"startLine":17,"endLine":19},"17":{"startLine":20,"endLine":21}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (!root) {\n    return vector<int>{};\n}\nvector<int> result;\nvector<TreeNode*> queue{root};\nsize_t head = 0;\nwhile (head < queue.size()) {\n    int row_max = -2147483648;\n    while (head < queue.size()) {\n        TreeNode* node = queue[static_cast<int>(head)];\n        head++;\n        row_max = max(row_max, 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    result.push_back(row_max);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":16,"16":17,"17":20,"18":22},"statementBundles":{"3":{"startLine":2,"endLine":3},"14":{"startLine":14,"endLine":15},"16":{"startLine":17,"endLine":19},"17":{"startLine":20,"endLine":21}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (root == null) {\n    return new ArrayList<>();\n}\nList<Integer> result = new ArrayList<>();\nList<TreeNode> queue = new ArrayList<>(List.of(root));\nint head = 0;\nwhile (head < queue.size()) {\n    int rowMax = -2147483648;\n    while (head < queue.size()) {\n        TreeNode node = queue.get(head);\n        head++;\n        rowMax = Math.max(rowMax, 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    result.add(rowMax);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":16,"16":17,"17":20,"18":22},"statementBundles":{"3":{"startLine":2,"endLine":3},"14":{"startLine":14,"endLine":15},"16":{"startLine":17,"endLine":19},"17":{"startLine":20,"endLine":21}}}}}},{"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 saved row width held the sweep together: each row reports the maximum over exactly its nodes, and the frozen count marks where one row ends.","Now push on the inputs. Two could stress the sweep: an empty tree, where root = null, and a tree with a row whose every value is negative."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"tree":[-1,-2,-3],"swapped":[0,1,2]}}]}},{"id":"edge-empty","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What should an empty tree return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-empty-state","state":{"root":"null"}}]},"summary":"The input is null: there is no root, so the sweep has nothing to seed its queue with.","options":[{"id":"empty-list","label":"An empty list, before any queue is built","rationale":"No nodes means no rows and no values. Guard the null root up front and return an empty list, so the sweep only runs once a node exists.","isCorrect":true},{"id":"list-zero","label":"A list holding a single 0","rationale":"An empty tree has no rows at all, so there is no value to report. The result is an empty list.","isCorrect":false},{"id":"read-root","label":"Let the sweep seed the queue and read the root anyway","rationale":"Seeding the queue with a null root and reading its value fails. The guard has to come before any queue work.","isCorrect":false}],"answer":"Guard the null root first and return an empty list, so the sweep starts only when a node exists."},{"id":"edge-negative","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What goes wrong if the row maximum starts at 0?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-neg-state","state":{"tree":[-1,-2,-3],"visited":[0],"swapped":[1,2]}}]},"summary":"Take a row whose nodes are -2 and -3, with the row maximum seeded at 0.","options":[{"id":"reports-zero","label":"It reports 0, a value outside the row","rationale":"Both -2 and -3 are below 0, so neither replaces the seed. The row reports 0, a number no node holds. Seed the row maximum below every possible value instead.","isCorrect":true},{"id":"reports-neg2","label":"It still reports -2, the real maximum","rationale":"Comparison keeps the larger, and 0 is larger than both -2 and -3, so the seed survives. The reported value is 0.","isCorrect":false},{"id":"no-effect","label":"Nothing, since the seed is overwritten by the first node","rationale":"The seed is overwritten only by a larger value. -2 is smaller than 0, so 0 stays. The starting value has to sit below any real node.","isCorrect":false}],"answer":"A seed of 0 can beat every node in an all-negative row and gets reported as the answer, so start the row maximum below any possible value."},{"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 weight: fix the row’s width before the pass, and start the row maximum below every possible value.","body":["Guard the empty tree, seed a queue with the root, and sweep while it holds nodes. Each pass: save the current width, start a fresh row maximum, weigh exactly that many nodes while enqueueing their children, and append the row maximum.","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":[3,1,5,9,2,null,4],"node":0}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the per-row sweep","eyebrow":"Code the rule","summary":"Now build the sweep: guard the empty tree, seed a queue with the root, then for each row save its width and start a fresh maximum, weigh exactly that many nodes while enqueueing their children, append the row maximum, and return the list once the queue empties.","workspacePanel":"code","checkpoints":[{"id":"check-empty","title":"Handle the empty tree","description":"Return an empty list when there is no root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"handles_empty_tree_return","scope":"check-empty","readMode":"tree-value-query-v1"}]},"commonMistakes":["Trying to enqueue a null root","Returning null instead of an empty list"],"hint":"Short-circuit before any queue setup.","semanticSpec":{"intent":"Handle the empty-tree boundary case before starting BFS.","doneWhen":"The function checks for a missing root and returns an empty list.","shouldFailWhen":"The code enqueues a missing root or returns a non-list placeholder.","roles":["root node","empty result"],"mustProve":["A missing root is checked before traversal setup.","The empty tree returns an empty list."],"mustNotAccept":["Queue setup before the empty-tree guard.","Returning null for an empty tree."],"equivalentVariants":["Use a falsy root check.","Use an explicit null check."],"proofSnippets":[{"id":"py-largest-row-empty-tree-return","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []"}]}},{"id":"init-structures","title":"Seed the BFS queue","description":"Create the result list and seed the traversal queue with the root node.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_bfs_result_and_queue","scope":"init-structures","readMode":"tree-value-query-v1"}]},"commonMistakes":["Creating a result list but never adding the root to the queue","Using a stack-style traversal"],"hint":"Start with one frontier containing only the root.","semanticSpec":{"intent":"Initialize the output collection and BFS frontier from the root.","doneWhen":"A result list exists and a queue-like frontier is seeded with the root.","shouldFailWhen":"The queue is never seeded with the root or the result collection is missing.","roles":["result list","BFS queue","root node"],"mustProve":["A result collection is initialized.","The root node is inserted into a queue-like frontier."],"mustNotAccept":["Creating a queue without the root.","Using a stack-style setup."],"equivalentVariants":["Use a list-backed queue with a head index.","Use a deque seeded with the root."],"proofSnippets":[{"id":"py-largest-row-init-result-and-queue","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]"}]}},{"id":"level-size","title":"Capture the row size","description":"Store the number of nodes currently in the frontier 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-row and next-row nodes in one maximum"],"hint":"Freeze the current frontier width at the start of each row.","semanticSpec":{"intent":"Capture the current frontier width before child nodes can extend the queue.","doneWhen":"The row size is stored at the start of a queue-driven row iteration.","shouldFailWhen":"The code reads the changing queue length while processing the row.","roles":["BFS queue","row size","frontier boundary"],"mustProve":["The traversal loop is driven by the queue frontier.","The current row width is captured before processing row nodes."],"mustNotAccept":["No stable boundary between current and next row.","Using the changing queue length as the inner-loop bound."],"equivalentVariants":["Store len(queue) - head before the row loop.","Store the current deque length before popping row nodes."],"proofSnippets":[{"id":"py-largest-row-capture-row-size","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            break\n        return result"}]}},{"id":"reset-aggregate","title":"Reset the row maximum","description":"Start each row with a fresh maximum before processing its nodes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"resets_level_aggregate_state","scope":"reset-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Letting the previous row's maximum carry into the next row","Resetting the maximum inside the inner loop"],"hint":"The row maximum should reset once per row.","semanticSpec":{"intent":"Start each row with a fresh aggregate state for that row's maximum.","doneWhen":"A row maximum is initialized inside the outer row loop before row nodes are processed.","shouldFailWhen":"The maximum carries over from a previous row or is reset for every node.","roles":["row maximum","row loop","aggregate state"],"mustProve":["The aggregate state is reset once per row.","The reset happens before the row's node-processing loop."],"mustNotAccept":["One global maximum shared by all rows.","Resetting the row maximum inside the node loop."],"equivalentVariants":["Initialize the row maximum to the minimum integer value.","Initialize the row maximum from the first value in the captured row."],"proofSnippets":[{"id":"py-largest-row-reset-row-maximum","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            row_max = -2147483648\n            for _ in range(row_size):\n                node = queue[head]\n                head += 1\n                row_max = max(row_max, node.val)\n            break\n        return result"}]}},{"id":"process-level","title":"Process exactly this row","description":"Consume exactly the captured number of nodes, update the row maximum, and enqueue children for later rows.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"processes_level_order_aggregate_nodes","scope":"process-level","readMode":"tree-value-query-v1"}]},"commonMistakes":["Forgetting to compare each node value","Processing nodes added for the next row too early","Forgetting to enqueue children"],"hint":"The inner loop should be bounded by the captured row size.","semanticSpec":{"intent":"Consume exactly the captured row, update the row maximum from node values, and enqueue children for later rows.","doneWhen":"A bounded inner loop advances through row nodes, compares each value into the row maximum, and appends children to the frontier.","shouldFailWhen":"The loop skips the value comparison, consumes next-row nodes early, or never enqueues children.","roles":["row nodes","row maximum","child frontier"],"mustProve":["The inner loop is bounded by the captured row size.","Each processed node can update the row maximum.","Child links are enqueued for later rows."],"mustNotAccept":["Processing without updating the maximum.","Processing without enqueueing children.","Using a loop bound that grows as children are added."],"equivalentVariants":["Use a head-index queue.","Use dequeue operations from a FIFO queue."],"proofSnippets":[{"id":"py-largest-row-process-captured-row","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            row_max = -2147483648\n            for _ in range(row_size):\n                node = queue[head]\n                head += 1\n                row_max = max(row_max, node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            break\n        return result"}]}},{"id":"emit-largest","title":"Append the row maximum","description":"After the row is processed, append the maximum found for that row.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"emits_level_aggregate_outcome","scope":"emit-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Appending before every node has been processed","Appending the node value without comparing against the row maximum"],"hint":"Append one value after the inner loop finishes.","semanticSpec":{"intent":"Emit one aggregate outcome for the completed row.","doneWhen":"The row maximum is appended after the row's bounded node loop finishes.","shouldFailWhen":"The code appends before the row is complete or appends a raw node value without the aggregate.","roles":["row maximum","result list","completed row"],"mustProve":["The row maximum is updated from row node values.","One row maximum is appended after row processing."],"mustNotAccept":["Appending once per node.","Appending before comparing all nodes in the row."],"equivalentVariants":["Append the row maximum to the result list.","Push the row maximum into the output collection."],"proofSnippets":[{"id":"py-largest-row-emit-row-maximum","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            row_max = -2147483648\n            for _ in range(row_size):\n                node = queue[head]\n                head += 1\n                row_max = max(row_max, node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            result.append(row_max)\n            break"}]}},{"id":"return-values","title":"Return all row maximums","description":"Return the collected row maximums after every row has been processed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_level_aggregate_result","scope":"return-aggregate","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning only the last row maximum","Returning the queue instead of the result"],"hint":"Return the result list after the BFS loop completes.","semanticSpec":{"intent":"Return the completed list of row maximums after BFS finishes.","doneWhen":"The terminal return uses the result collection populated by the row aggregate loop.","shouldFailWhen":"The function returns only the last maximum, the queue, or no value.","roles":["result list","row maximums","terminal return"],"mustProve":["The result collection receives row maximums.","The terminal return reads that result collection."],"mustNotAccept":["Returning the active queue.","Returning the last row maximum scalar.","No terminal return of the aggregate output."],"equivalentVariants":["Return the result list directly.","Return an alias that stores the row maximum output."],"proofSnippets":[{"id":"py-largest-row-return-results","language":"python","code":"class Solution:\n    def largestValues(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            row_size = len(queue) - head\n            row_max = -2147483648\n            for _ in range(row_size):\n                node = queue[head]\n                head += 1\n                row_max = max(row_max, node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            result.append(row_max)\n        return result"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Carry it forward","summary":"You swept the tree row by row and kept the largest value of each pass.","workspacePanel":"code","body":["Largest value per row is breadth-first search plus one rule: over each row, keep the maximum. The row boundary, saved from the frontier width before the pass, is what 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 right side view."],"takeaways":[{"title":"A row’s answer needs every node at its depth","body":"The largest value can descend from any node above it, so chasing the previous row’s winner misses it. On the tree, 9 sits under 1, the smaller row-two node."},{"title":"Save the row width before the pass","body":"Lock in the frontier’s width first. That count bounds the row, so children enqueued mid-pass wait for the next row instead of collapsing every row into one maximum."},{"title":"Seed the row maximum below every value","body":"Start each row’s maximum lower than any node could be, so an all-negative row like -2 and -3 reports -2 rather than a stray 0."}],"nextAction":"Submit your solution to run it against every test case."}],"slidesOrigin":"authored"}}
