{"id":"average-of-levels-in-binary-tree","title":"Average of Levels in Binary Tree","difficulty":"easy","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 average value of the nodes on each level from top to bottom.\n\nEach average should be computed from exactly the nodes that belong to that level.","examples":[{"input":"root = {\"val\": 3, \"left\": {\"val\": 9}, \"right\": {\"val\": 20, \"left\": {\"val\": 15}, \"right\": {\"val\": 7}}}","output":"[3, 14.5, 11]","explanation":"Level 0 average is 3. Level 1 average is (9 + 20) / 2 = 14.5. Level 2 average is (15 + 7) / 2 = 11."},{"input":"root = {\"val\": 1, \"left\": {\"val\": 2}, \"right\": {\"val\": 3}}","output":"[1, 2.5]","explanation":"The second level contains 2 and 3, so its average is 2.5."},{"input":"root = null","output":"[]","explanation":"An empty tree has no levels."}],"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 averageOfLevels(self, root: TreeNode) -> list[float]:\n        # Your code here\n        pass","functionName":"averageOfLevels","testCases":[{"id":"1","input":{"root":{"val":3,"left":{"val":9,"left":null,"right":null,"__id__":"tree-1"},"right":{"val":20,"left":{"val":15,"left":null,"right":null,"__id__":"tree-3"},"right":{"val":7,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[3,14.5,11],"description":"Canonical three-level tree."},{"id":"2","input":{"root":{"val":-10,"left":null,"right":null,"__id__":"tree-0"}},"expected":[-10],"description":"Single node with a negative value."},{"id":"3","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":7,"left":null,"right":null,"__id__":"tree-6"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[1,2.5,5.5],"description":"Complete tree with two fractional averages."},{"id":"4","input":{"root":{"val":5,"left":{"val":3,"left":{"val":1,"left":null,"right":null,"__id__":"tree-2"},"right":null,"__id__":"tree-1"},"right":null,"__id__":"tree-0"}},"expected":[5,3,1],"description":"Left-skewed tree where each level has one node."},{"id":"5","input":{"root":{"val":10,"left":{"val":-10,"left":null,"right":{"val":-30,"left":null,"right":null,"__id__":"tree-3"},"__id__":"tree-1"},"right":{"val":20,"left":{"val":30,"left":null,"right":null,"__id__":"tree-4"},"right":null,"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[10,5,0],"description":"Mixed positive and negative values."},{"id":"h1","input":{"root":null},"expected":[],"description":"Empty tree."},{"id":"h2","input":{"root":{"val":1,"left":null,"right":{"val":2,"left":null,"right":{"val":3,"left":null,"right":{"val":4,"left":null,"right":null,"__id__":"tree-3"},"__id__":"tree-2"},"__id__":"tree-1"},"__id__":"tree-0"}},"expected":[1,2,3,4],"description":"Right-skewed tree."},{"id":"h3","input":{"root":{"val":100,"left":{"val":-50,"left":{"val":-100,"left":null,"right":null,"__id__":"tree-3"},"right":{"val":0,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-1"},"right":{"val":50,"left":{"val":0,"left":null,"right":null,"__id__":"tree-5"},"right":{"val":100,"left":null,"right":null,"__id__":"tree-6"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[100,0,0],"description":"Large positive and negative values cancel at lower levels."},{"id":"h4","input":{"root":{"val":8,"left":{"val":4,"left":{"val":2,"left":null,"right":null,"__id__":"tree-3"},"right":{"val":6,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-1"},"right":{"val":10,"left":{"val":9,"left":null,"right":null,"__id__":"tree-5"},"right":{"val":11,"left":null,"right":null,"__id__":"tree-6"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[8,7,7]},{"id":"h5","input":{"root":{"val":1,"left":{"val":-1,"left":{"val":-2,"left":null,"right":null,"__id__":"tree-3"},"right":null,"__id__":"tree-1"},"right":{"val":3,"left":{"val":2,"left":null,"right":null,"__id__":"tree-4"},"right":{"val":4,"left":null,"right":null,"__id__":"tree-5"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[1,1,1.3333333333333333]}],"hints":[{"level":1,"content":"Each answer entry belongs to one tree level, so separate the current level from the next one before adding children.","revealPattern":false},{"level":2,"content":"Use a queue and capture the queue size at the start of each level.","revealPattern":true},{"level":3,"content":"For each level, reset a sum, process exactly level_size nodes, then append sum / level_size.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which traversal keeps a whole depth grouped as you go?","decisionPrompt":"Pick the traversal whose state lets you total one depth and divide it before moving on.","approaches":[{"id":"bfs-level-aggregate","name":"Queue-based BFS","summary":"A queue fans out from the root one depth at a time, so every node at the current depth sits together in the queue before any deeper node is reached.","decisionReason":"A breadth-first frontier holds one whole depth at once, which is exactly the group each average is taken over.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Holds up to one depth of nodes in the queue, and visits each node once."],"isOptimal":true,"steps":["Seed the queue with the root.","Fan out depth by depth, the children of one depth queueing behind it.","Handle a whole depth as the group currently waiting in the queue.","Move to the next depth once the current one is done."]},{"id":"dfs-depth-buckets","name":"DFS with depth buckets","summary":"Recurse down each branch, tagging every node with its depth, so a depth's nodes are reached at scattered moments and have to be tallied into a running sum and count bucket per depth.","decisionReason":"Depth-indexed DFS computes the same average for every level. This flow uses a queue because one level's sum, count, and boundary stay visible together.","complexity":{"time":"O(n)","space":"O(d + h)"},"tradeoffs":["No explicit queue, but it holds a sum and count bucket for every depth, plus the recursion stack down one branch."],"isViable":true,"isOptimal":false,"steps":["Recurse with a depth argument.","Tag each node with its depth as the dive reaches it.","Reconcile each depth's scattered nodes after the walk."]}]},"codingCheckpoints":[{"id":"check-empty","title":"Guard the empty tree","description":"Return an empty list immediately when the root is null.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"handles_empty_tree_return","scope":"check-empty","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Return an empty result for a null root before any traversal begins.","doneWhen":"A null root returns an empty list up front.","shouldFailWhen":"A null root falls through into the queue setup.","roles":["root","result"],"mustProve":["a null root returns an empty list before the search starts"],"mustNotAccept":["a null root is enqueued or dereferenced"],"proofSnippets":[{"id":"py-average-empty-guard","language":"python","code":"class Solution:\n    def averageOfLevels(self, root):\n        if not root:\n            return []"}]},"commonMistakes":["Letting a null root reach the queue, then reading .val on it","Returning null instead of an empty list"],"hint":"If the root is null, return an empty list before doing anything else."},{"id":"init-structures","title":"Seed the queue and result","description":"Create the result list and a queue holding just 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"}]},"semanticSpec":{"intent":"Initialize an empty result list and a BFS queue seeded with the root.","doneWhen":"A result list exists and the queue starts holding the root.","shouldFailWhen":"The queue starts empty, so the loop never runs.","roles":["queue","result","root"],"mustProve":["a result list is created and a queue is initialized holding the root node"],"mustNotAccept":["the queue starts empty","a stack-style traversal is set up instead of a queue"],"proofSnippets":[{"id":"py-average-init-result-and-queue","language":"python","code":"class Solution:\n    def averageOfLevels(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]"}]},"commonMistakes":["Creating a result list but never adding the root to the queue","Using a stack-style traversal"],"hint":"Start one frontier containing only the root, plus an empty result list."},{"id":"level-size","title":"Snapshot the depth count","description":"Capture how many nodes are in the queue before processing the depth.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"captures_bfs_level_boundary","scope":"level-size","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Capture the current queue length as the depth boundary before processing the depth.","doneWhen":"The queue size is snapshotted into a variable before the inner loop runs.","shouldFailWhen":"The count is read live during processing, after children have been enqueued.","roles":["queue","level size"],"mustProve":["the queue length is captured before the inner loop, bounding the depth"],"mustNotAccept":["the count is taken after children are enqueued","no depth boundary is captured"],"proofSnippets":[{"id":"py-average-capture-level-size","language":"python","code":"class Solution:\n    def averageOfLevels(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\n        while head < len(queue):\n            level_size = len(queue) - head\n            break\n        return result"}]},"commonMistakes":["Using the changing queue length inside the inner loop","Mixing this depth and the next into one average"],"hint":"Record the queue’s length into a variable before the inner loop starts."},{"id":"reset-aggregate","title":"Reset the running total","description":"Start each depth with a fresh sum 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"}]},"semanticSpec":{"intent":"Start every depth with a fresh running total before its nodes are processed.","doneWhen":"The sum resets to zero once per depth, before the inner loop.","shouldFailWhen":"The previous depth’s total carries into the next, or the sum resets inside the inner loop.","roles":["level sum","level size"],"mustProve":["the running total is reset once per depth before its nodes are summed"],"mustNotAccept":["the previous depth’s total carries forward","the sum is reset inside the inner loop"],"proofSnippets":[{"id":"py-average-reset-level-sum","language":"python","code":"class Solution:\n    def averageOfLevels(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\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            break\n        return result"}]},"commonMistakes":["Letting the previous depth’s total carry into the next","Resetting the sum inside the inner loop"],"hint":"The total should reset once per depth, just before the inner loop."},{"id":"process-level","title":"Total exactly this depth","description":"Consume exactly the snapshotted number of nodes, add each value to the total, and enqueue their children.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"processes_level_order_aggregate_nodes","scope":"process-level","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Process exactly the snapshotted count of nodes, adding each value to the depth total and enqueuing children.","doneWhen":"Each depth pops snapshot-many nodes, adds their values to the total, and enqueues their children.","shouldFailWhen":"Children are summed into the current depth, or the inner loop is not bounded by the snapshot.","roles":["queue","level sum","level size"],"mustProve":["exactly the snapshotted count of nodes is summed, with children enqueued for the next depth"],"mustNotAccept":["children are added to the current depth’s total","the inner loop is unbounded by the snapshot"],"proofSnippets":[{"id":"py-average-process-captured-level","language":"python","code":"class Solution:\n    def averageOfLevels(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\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            break\n        return result"}]},"commonMistakes":["Forgetting to enqueue children","Summing next-depth nodes into this depth"],"hint":"Loop snapshot-many times: pop the front node, add its value, and enqueue its non-null children."},{"id":"emit-average","title":"Record the depth average","description":"After the depth is totalled, append the sum divided by the snapshotted count.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"emits_level_aggregate_outcome","scope":"emit-average","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Append one average per depth: the running total divided by the snapshotted node count.","doneWhen":"After the inner loop, the total divided by the snapshot is appended once.","shouldFailWhen":"The raw sum is appended, the divisor is the live queue length, or the append happens inside the inner loop.","roles":["result","level sum","level size"],"mustProve":["the recorded value is the depth total divided by the snapshotted count, appended once after the depth"],"mustNotAccept":["the raw total is appended instead of the average","the divisor is the current queue length rather than the snapshot"],"proofSnippets":[{"id":"py-average-emit-level-average","language":"python","code":"class Solution:\n    def averageOfLevels(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\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 / level_size)\n            break"}]},"commonMistakes":["Appending the raw total instead of the average","Dividing by the current queue length instead of the snapshot"],"hint":"Divide the total by the count you snapshotted, after the inner loop finishes."},{"id":"return-averages","title":"Return all the averages","description":"Return the collected averages after every depth has been processed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_level_aggregate_result","scope":"return-averages","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Return the accumulated list of per-depth averages after the sweep completes.","doneWhen":"The list of averages is returned once the queue is empty.","shouldFailWhen":"Only the last average is returned, or the queue is returned instead of the result.","roles":["result"],"mustProve":["the full list of per-depth averages is returned after the sweep"],"mustNotAccept":["only the last average is returned","the queue is returned instead of the result"],"proofSnippets":[{"id":"py-average-return-results","language":"python","code":"class Solution:\n    def averageOfLevels(self, root):\n        if not root:\n            return []\n        result = []\n        queue = [root]\n        head = 0\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 / level_size)\n        return result"}]},"commonMistakes":["Returning only the last average","Returning the queue instead of the result"],"hint":"Return the result list after the BFS loop completes."}],"slides":[{"id":"the-task","chapter":"Read the signal","kind":"info","eyebrow":"Read the problem","title":"One average for every depth","workspacePanel":"problem","body":["You are given the root of a binary tree and must return the average value of the nodes at each depth, from the top down. The root sits at depth 0, its children at depth 1, and so on.","The obvious first cut is to handle the depths one at a time: gather every node at depth 0 and average them, then gather every node at depth 1, and so on. Watch that work, and watch what each pass costs."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"task","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2]}}]}},{"id":"rescan-per-depth","chapter":"The obvious way","kind":"code-trace","eyebrow":"The obvious way","title":"Re-walk the tree once for each depth","summary":"Re-descending from the root for every depth gets each average right, but the shallow nodes get re-walked on every pass. Watch how much of the tree the deepest passes retrace.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def averageOfLevels(root: TreeNode | None) -> list[float]:\n    def nodes_at_depth(node: TreeNode | None, depth: int) -> list[int]:\n        if node is None:\n            return []\n        if depth == 0:\n            return [node.val]\n        return nodes_at_depth(node.left, depth - 1) + nodes_at_depth(node.right, depth - 1)\n\n    result = []\n    depth = 0\n    while True:\n        level = nodes_at_depth(root, depth)\n        if len(level) == 0:\n            break\n        total = 0\n        for value in level:\n            total += value\n        result.append(total / len(level))\n        depth += 1\n    return result","steps":[{"id":"scan-depth0","title":"Depth 0: walk from the root to gather one node","codeLine":12,"summary":"Tree [3, 9, 20, null, null, 15, 7]. To collect depth 0, walk down from the root and keep only nodes at depth 0: just 3.","state":{"tree":[3,9,20,null,null,15,7],"node":0,"visited":[0]}},{"id":"record-depth0","title":"Average depth 0, then start the next depth over","codeLine":18,"summary":"3 over 1 records 3. To collect depth 1, the walk restarts at the root and descends again, this time keeping 9 and 20.","state":{"tree":[3,9,20,null,null,15,7],"node":0,"swapped":[1,2],"visited":[0]}},{"id":"scan-depth2","title":"Depth 2: walk from the root yet again","codeLine":12,"summary":"To collect depth 2, the walk starts at the root a third time and passes through 3 and 20 before reaching 15 and 7. Every depth re-descends from the top.","state":{"tree":[3,9,20,null,null,15,7],"swapped":[5,6],"visited":[0,2]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function nodesAtDepth(node, depth) {\n    if (node === null) {\n        return [];\n    }\n    if (depth === 0) {\n        return [node.val];\n    }\n    return nodesAtDepth(node.left, (depth - 1)).concat(nodesAtDepth(node.right, (depth - 1)));\n}\nconst result = [];\nlet depth = 0;\nwhile (true) {\n    const level = nodesAtDepth(root, depth);\n    if (level.length === 0) {\n        break;\n    }\n    let total = 0;\n    for (const value of level) {\n        total += value;\n    }\n    result.push((total / level.length));\n    depth++;\n}\nreturn result;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15,"15":17,"16":18,"17":19,"18":21,"19":22,"20":24},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"7":{"startLine":8,"endLine":9},"14":{"startLine":15,"endLine":16},"17":{"startLine":19,"endLine":20},"19":{"startLine":22,"endLine":23}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function nodesAtDepth(node: TreeNode | null, depth: number): Array<number> {\n    if (node === null) {\n        return [];\n    }\n    if (depth === 0) {\n        return [node.val];\n    }\n    return nodesAtDepth(node.left, (depth - 1)).concat(nodesAtDepth(node.right, (depth - 1)));\n}\nconst result: Array<number> = [];\nlet depth = 0;\nwhile (true) {\n    const level = nodesAtDepth(root, depth);\n    if (level.length === 0) {\n        break;\n    }\n    let total = 0;\n    for (const value of level) {\n        total += value;\n    }\n    result.push((total / level.length));\n    depth++;\n}\nreturn result;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15,"15":17,"16":18,"17":19,"18":21,"19":22,"20":24},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"7":{"startLine":8,"endLine":9},"14":{"startLine":15,"endLine":16},"17":{"startLine":19,"endLine":20},"19":{"startLine":22,"endLine":23}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static List<Integer> nodesAtDepth(TreeNode node, int depth) {\n    if (node == null) {\n        return new ArrayList<>();\n    }\n    if (depth == 0) {\n        return List.of(node.val);\n    }\n    List<Integer> result = new ArrayList<>(nodesAtDepth(node.left, (depth - 1)));\n    result.addAll(nodesAtDepth(node.right, (depth - 1)));\n    return result;\n}\n\nList<Double> result = new ArrayList<>();\nint depth = 0;\nwhile (true) {\n    List<Integer> level = nodesAtDepth(root, depth);\n    if (level.isEmpty()) {\n        break;\n    }\n    int total = 0;\n    for (Integer value : level) {\n        total += value;\n    }\n    result.add(((double)total / level.size()));\n    depth++;\n}\nreturn result;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"9":13,"10":14,"11":15,"12":16,"13":17,"14":18,"15":20,"16":21,"17":22,"18":24,"19":25,"20":27},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"7":{"startLine":8,"endLine":11},"14":{"startLine":18,"endLine":19},"17":{"startLine":22,"endLine":23},"19":{"startLine":25,"endLine":26}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> NodesAtDepth(TreeNode node, int depth) {\n    if (node == null) {\n        return new List<int>();\n    }\n    if (depth == 0) {\n        return new List<int> { node.val };\n    }\n    return NodesAtDepth(node.left, depth - 1).Concat(NodesAtDepth(node.right, depth - 1)).ToList();\n    return null;\n}\nList<double> result = new();\nint depth = 0;\nwhile (true) {\n    List<int> level = NodesAtDepth(root, depth);\n    if (level.Count == 0) {\n        break;\n    }\n    int total = 0;\n    foreach (int value in level) {\n        total += value;\n    }\n    result.Add((total / (double)(level.Count)));\n    depth++;\n}\nreturn result;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":18,"16":19,"17":20,"18":22,"19":23,"20":25},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"7":{"startLine":8,"endLine":10},"14":{"startLine":16,"endLine":17},"17":{"startLine":20,"endLine":21},"19":{"startLine":23,"endLine":24}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<vector<int>(TreeNode*, int)> nodes_at_depth;\n\nnodes_at_depth = [&]( TreeNode* node, int depth ) -> vector<int> {\n    if (node == nullptr) {\n        return vector<int>{};\n    }\n    if (depth == 0) {\n        return vector<int>{node->val};\n    }\n    vector<int> result = nodes_at_depth(node->left, (depth - 1));\n    vector<int> right_values = nodes_at_depth(node->right, (depth - 1));\n    result.insert(result.end(), right_values.begin(), right_values.end());\n    return result;\n};\nvector<double> result;\nint depth = 0;\nwhile (true) {\n    vector<int> level = nodes_at_depth(root, depth);\n    if (level.empty()) {\n        break;\n    }\n    int total = 0;\n    for (int value : level) {\n        total += value;\n    }\n    result.push_back((static_cast<double>(total) / level.size()));\n    depth++;\n}\nreturn result;","lineMap":{"3":4,"4":5,"5":7,"6":8,"7":10,"9":15,"10":16,"11":17,"12":18,"13":19,"14":20,"15":22,"16":23,"17":24,"18":26,"19":27,"20":29},"statementBundles":{"4":{"startLine":5,"endLine":6},"6":{"startLine":8,"endLine":9},"7":{"startLine":10,"endLine":14},"14":{"startLine":20,"endLine":21},"17":{"startLine":24,"endLine":25},"19":{"startLine":27,"endLine":28}}}}}},{"id":"rescan-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Count the work","title":"Across all depths, how much work do the repeated nodes_at_depth walks add up to?","workspacePanel":"trace","summary":"A one-branch tree has n nodes spread over n depths. Each nodes_at_depth(root, depth) call starts again from the root.","options":[{"id":"n-times-height","label":"About n descents of up to n nodes each, roughly n times the height","rationale":"Each depth re-walks from the root, and a one-branch tree of n nodes is n deep, so the deepest passes touch nearly every node again. The repeated descents pile up to about n times the height.","isCorrect":true},{"id":"single-pass","label":"One pass over the tree, since each node is averaged once","rationale":"Each node is averaged once, but to find a node at depth d the walk re-descends past every shallower node first, so the tree is traversed once per depth, not once total.","isCorrect":false},{"id":"constant-extra","label":"A constant amount of extra work per depth","rationale":"A pass for depth d is not constant: it walks every node down to depth d, so deeper passes cost more, and on a skewed tree the last pass alone nearly retraces the whole tree.","isCorrect":false}],"answer":"Re-descending for every depth costs about n times the height. The repeated walks are the waste to remove: each node should be touched once."},{"id":"what-each-answer-needs","chapter":"The idea","kind":"case-probe","eyebrow":"Find the state","title":"What do you need before you can record one depth’s average?","workspacePanel":"visualizer","summary":"Depth 1 holds 9 and 20, and its answer is 14.5.","options":[{"id":"sum-and-count","label":"The total of that depth’s values and how many nodes are in it","rationale":"An average is a sum over a count, so 9 plus 20 is 29 and the count is 2, which gives 14.5. Both numbers come from exactly this depth.","isCorrect":true},{"id":"sum-only","label":"Just the running total of the values seen so far","rationale":"A total alone gives 29 but no divisor; without the node count you cannot turn it into 14.5.","isCorrect":false},{"id":"max-min","label":"The largest and smallest value at the depth","rationale":"The average is not the midpoint of the extremes; 9 and 20 average to 14.5, which their range does not give you.","isCorrect":false}],"answer":"You need both the depth’s total and its node count. 29 over 2 nodes is 14.5.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"need","state":{"tree":[3,9,20,null,null,15,7],"node":1,"swapped":[1,2],"visited":[0]}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which traversal keeps a whole depth grouped as you go?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach","state":{"tree":[3,9,20,null,null,15,7],"node":0,"swapped":[1,2]}}]}},{"id":"frontier-count","chapter":"The idea","kind":"case-probe","eyebrow":"Find the state","title":"When a depth begins, what does the breadth-first frontier’s size tell you?","workspacePanel":"visualizer","summary":"The root has been processed, and 9 and 20 are waiting in the queue.","options":[{"id":"depth-count","label":"Exactly how many nodes are at the depth about to be processed","rationale":"Right now the queue holds 9 and 20 and nothing else, so its size, 2, is precisely this depth’s node count, the divisor you need.","isCorrect":true},{"id":"all-remaining","label":"How many nodes are left in the whole tree","rationale":"Deeper nodes such as 15 and 7 are not enqueued until their parents are processed, so the queue is never the whole remainder.","isCorrect":false},{"id":"recorded","label":"How many averages have been recorded so far","rationale":"Recorded averages live in the result list; the queue holds nodes still waiting to be visited.","isCorrect":false}],"answer":"When a depth begins, the queue holds exactly that depth’s nodes, so its size is the count to divide by.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frontier","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2],"arrays":[{"name":"queue","values":[9,20]}]}}]}},{"id":"snapshot-the-count","chapter":"The idea","kind":"case-probe","eyebrow":"Find the trap","title":"As you process this depth you enqueue its children. So how do you keep the count it started with?","workspacePanel":"visualizer","summary":"The queue holds 9 and 20. Processing 20 will push 15 and 7 onto the same queue.","options":[{"id":"snapshot","label":"Read the queue’s size once, before the depth, and reuse that number","rationale":"The size, 2, is taken before any child is added, so it stays the right total and the right divisor even as 15 and 7 join the queue behind them.","isCorrect":true},{"id":"live-length","label":"Read the queue’s length again when you divide","rationale":"By the time you divide, 15 and 7 have been enqueued, so the length has changed and no longer counts this depth.","isCorrect":false},{"id":"until-empty","label":"Process the queue until it is empty, then divide once","rationale":"Emptying the queue merges every depth into one total; you would divide the whole tree by one number instead of one depth at a time.","isCorrect":false}],"answer":"Snapshot the size once before the depth. That single number is both how many to total and what to divide by.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"snapshot","state":{"tree":[3,9,20,null,null,15,7],"node":2,"visited":[0],"swapped":[1,2],"level_size":2,"arrays":[{"name":"queue","values":[9,20,15,7]}]}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it sweep","title":"Snapshot, total, divide","workspacePanel":"visualizer","body":["The queue fans out from the root one depth at a time. Each pass snapshots how many nodes are waiting, totals exactly that many values while their children queue up behind them, and divides by that same snapshot.","Watch it run on [3, 9, 20, null, null, 15, 7] and work out each depth’s average yourself as the pass reaches it."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"tree":[3,9,20,null,null,15,7],"node":0,"arrays":[{"name":"queue","values":[3]}]}}]}},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the sweep","title":"Average three depths","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"d-snapshot","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2],"level_size":2,"level_sum":0,"arrays":[{"name":"queue","values":[9,20]}]}},{"id":"d-children","state":{"tree":[3,9,20,null,null,15,7],"node":2,"visited":[0,1],"swapped":[5,6],"level_size":2,"level_sum":29,"arrays":[{"name":"queue","values":[15,7]}]}},{"id":"d-divide","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2],"swapped":[5,6],"level_size":2,"level_sum":29,"arrays":[{"name":"queue","values":[15,7]}]}}]},"beats":[{"id":"d-snapshot","title":"Depth 1 is about to start. What gets locked in first?","summary":"The waiting line holds 9 and 20.","prompt":"You are at the top of this pass.","options":[{"id":"size","label":"The queue size, 2, as this depth’s count","rationale":"Snapshot 2 before touching the queue: it is both how many nodes to total and what to divide the total by.","isCorrect":true},{"id":"first","label":"Just the first node, 9","rationale":"One node does not bound the depth; you would divide 29 by the wrong count. Lock in the full size up front.","isCorrect":false},{"id":"nothing","label":"Nothing, divide once the queue is empty","rationale":"Emptying the queue totals every depth together and loses the per-depth average.","isCorrect":false}],"answer":"Lock in the queue size, 2, before any child is enqueued. That count is the divisor for this depth."},{"id":"d-children","title":"As 9 and 20 are totalled, where do 15 and 7 go?","summary":"You are partway through depth 1; 20’s children are 15 and 7.","prompt":"The running total is climbing toward 29.","options":[{"id":"back","label":"To the back of the queue, for the next depth","rationale":"Children wait behind the current depth. The count was already snapshotted, so 15 and 7 do not change this depth’s total or its divisor.","isCorrect":true},{"id":"current","label":"Into this depth’s total","rationale":"15 and 7 are a depth deeper than 9 and 20. Adding them would make the average cover two depths at once.","isCorrect":false},{"id":"now","label":"Processed immediately after their parent","rationale":"Handling them now would interleave depths; enqueue them and let the bounded pass finish first.","isCorrect":false}],"answer":"To the back of the queue. They form the next depth and wait, leaving 29 over 2 as 14.5."},{"id":"d-divide","title":"Depth 1’s two nodes are done. What is recorded, and what happens next?","summary":"The total is 29 and the snapshot was 2.","prompt":"Both nodes of depth 1 have been totalled.","options":[{"id":"divide-repeat","label":"Record 29 over 2 as 14.5, then snapshot the new queue size and repeat","rationale":"Dividing the total by the snapshot gives 14.5. The queue now holds 15 and 7, so a fresh total begins on the new size.","isCorrect":true},{"id":"raw","label":"Record the raw total, 29","rationale":"The answer asks for an average. 29 must be divided by the count, 2, to get 14.5.","isCorrect":false},{"id":"stop","label":"Stop, the tree is done","rationale":"The queue still holds 15 and 7, so the sweep continues until the queue empties.","isCorrect":false}],"answer":"Record 14.5, then snapshot the new size, 2, and sweep depth 2 to record 22 over 2 as 11."}]},{"id":"live-divisor-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could you reset the running total right where each node is read?","workspacePanel":"trace","summary":"Moving the reset next to the node read looks tidy, and it saves a separate line before the depth. A one-node depth like the root still passes. Watch what happens when a depth has two nodes.","pitfall":"This version tucks the level_sum reset inside the inner loop, next to the node read, instead of once before the depth's nodes are totalled.","whyItMatters":"Reset the total once per depth, before the inner loop, not on every node inside it. Clearing level_sum at the top of the inner loop wipes every earlier node in the depth, so only the last node survives into the divide. On the canonical tree depth 1 holds 9 and 20: 9 is added, then the reset clears it, 20 is added alone, and it records 20 over 2 as 10 instead of 14.5.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\nqueue = [root]\nwhile queue:\n    level_size = len(queue)\n    level_sum = 0\n    i = 0\n    while i < level_size:\n        level_sum = 0\n        node = queue.pop(0)\n        level_sum += node.val\n        if node.left:\n            queue.append(node.left)\n        if node.right:\n            queue.append(node.right)\n        i += 1\n    result.append(level_sum / level_size)\nreturn result","steps":[{"id":"pit-depth0","title":"Depth 0: the lone root totals to 3","codeLine":16,"summary":"Tree [3, 9, 20, null, null, 15, 7]. Depth 0 holds only the root, so its single node 3 records 3 over 1 as 3, and a one-node depth hides the bug.","state":{"tree":[3,9,20,null,null,15,7],"node":0,"visited":[0]}},{"id":"pit-add-first","title":"Depth 1’s first node 9 is reset to zero, then added","codeLine":10,"summary":"Depth 1 holds 9 and 20. The inner loop opens on 9: level_sum is cleared to 0, then 9 is added, so the total reads 9.","state":{"tree":[3,9,20,null,null,15,7],"node":1,"visited":[0],"swapped":[1]}},{"id":"pit-reset-wipes","title":"The next node clears the total again, dropping 9","codeLine":8,"summary":"On node 20 the inner loop runs level_sum = 0 once more, so the 9 already counted is wiped. 20 is then added to a total that starts back at zero.","state":{"tree":[3,9,20,null,null,15,7],"node":2,"visited":[0,1],"swapped":[2]}},{"id":"pit-wrong","title":"Depth 1 records 10, not 14.5","codeLine":16,"summary":"Only 20 survived the per-node reset, so the total is 20, and 20 over 2 records 10. The two-node average lost 9 entirely.","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nconst queue = [root];\nwhile (queue.length > 0) {\n    const levelSize = queue.length;\n    let levelSum = 0;\n    let i = 0;\n    while (i < levelSize) {\n        levelSum = 0;\n        const node = queue.shift();\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        i++;\n    }\n    result.push((levelSum / levelSize));\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14,"14":15,"15":17,"16":19,"17":21},"statementBundles":{"12":{"startLine":12,"endLine":13},"14":{"startLine":15,"endLine":16},"15":{"startLine":17,"endLine":18},"16":{"startLine":19,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<number> = [];\nconst queue = [root];\nwhile (queue.length > 0) {\n    const levelSize = queue.length;\n    let levelSum = 0;\n    let i = 0;\n    while (i < levelSize) {\n        levelSum = 0;\n        const node = queue.shift()!;\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        i++;\n    }\n    result.push((levelSum / levelSize));\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14,"14":15,"15":17,"16":19,"17":21},"statementBundles":{"12":{"startLine":12,"endLine":13},"14":{"startLine":15,"endLine":16},"15":{"startLine":17,"endLine":18},"16":{"startLine":19,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Double> result = new ArrayList<>();\nList<TreeNode> queue = new ArrayList<>(List.of(root));\nwhile (!queue.isEmpty()) {\n    int levelSize = queue.size();\n    int levelSum = 0;\n    int i = 0;\n    while (i < levelSize) {\n        levelSum = 0;\n        TreeNode node = queue.remove(0);\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        i++;\n    }\n    result.add(((double)levelSum / levelSize));\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14,"14":15,"15":17,"16":19,"17":21},"statementBundles":{"12":{"startLine":12,"endLine":13},"14":{"startLine":15,"endLine":16},"15":{"startLine":17,"endLine":18},"16":{"startLine":19,"endLine":20}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<double> result = new();\nQueue<TreeNode> queue = new(new[] { root });\nwhile (queue.Count > 0) {\n    int levelSize = queue.Count;\n    int levelSum = 0;\n    int i = 0;\n    while (i < levelSize) {\n        levelSum = 0;\n        TreeNode node = queue.Dequeue();\n        levelSum += node.val;\n        if (node.left != null) {\n            queue.Enqueue(node.left);\n        }\n        if (node.right != null) {\n            queue.Enqueue(node.right);\n        }\n        i++;\n    }\n    result.Add((levelSum / (double)(levelSize)));\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":14,"14":15,"15":17,"16":19,"17":21},"statementBundles":{"12":{"startLine":12,"endLine":13},"14":{"startLine":15,"endLine":16},"15":{"startLine":17,"endLine":18},"16":{"startLine":19,"endLine":20}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<double> result;\ndeque<TreeNode*> queue{root};\nwhile (!queue.empty()) {\n    int level_size = queue.size();\n    int level_sum = 0;\n    int i = 0;\n    while (i < level_size) {\n        level_sum = 0;\n        TreeNode* node = queue.front();\n        queue.pop_front();\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        i++;\n    }\n    result.push_back((static_cast<double>(level_sum) / level_size));\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":11,"11":12,"12":13,"13":15,"14":16,"15":18,"16":20,"17":22},"statementBundles":{"9":{"startLine":9,"endLine":10},"12":{"startLine":13,"endLine":14},"14":{"startLine":16,"endLine":17},"15":{"startLine":18,"endLine":19},"16":{"startLine":20,"endLine":21}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Stress the idea","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The snapshot-and-divide pass holds for the canonical tree. Before coding it, try to break it on the shapes that sit at the edges of the rule.","Three inputs sit right at those edges: a null root with no node at all, a tree of a single node, and a depth whose two values are 9 and 20."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge","state":{"tree":[5],"visited":[0]}}]}},{"id":"edge-empty","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the idea","title":"What should come back when the root is null?","workspacePanel":"visualizer","summary":"There is no node at any depth.","options":[{"id":"empty-list","label":"An empty list, returned before the queue is built","rationale":"No nodes means no depths and no averages, so the answer is the empty list, and seeding the queue with a null would break the first total.","isCorrect":true},{"id":"zero","label":"A list holding 0","rationale":"There is no depth to average, so the result has no entries at all. A result entry of 0 would invent a depth.","isCorrect":false},{"id":"null","label":"Null","rationale":"The function returns a list of averages; with no nodes that list is empty, not absent.","isCorrect":false}],"answer":"Return an empty list, guarded before the queue is ever seeded with a node.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty","state":{"root":"null"}}]}},{"id":"edge-fractional","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the idea","title":"A depth holds 9 and 20. What must the recorded average be?","workspacePanel":"visualizer","summary":"The total is 29 and the count is 2.","options":[{"id":"fractional","label":"14.5, keeping the fractional part","rationale":"29 over 2 is 14.5. The average must keep the fraction, because two nodes rarely divide evenly.","isCorrect":true},{"id":"truncated","label":"14, dropping the remainder","rationale":"Truncating to 14 keeps the traversal correct but records the wrong number; the expected answer is 14.5.","isCorrect":false},{"id":"rounded","label":"15, rounded up","rationale":"The average is not rounded to a neighboring whole number; 29 over 2 is exactly 14.5.","isCorrect":false}],"answer":"14.5. Divide so the fractional part survives rather than truncating to 14.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frac","state":{"tree":[3,9,20,null,null,15,7],"node":1,"swapped":[1,2],"visited":[0]}}]}},{"id":"edge-single","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the idea","title":"The tree is a single node, value 5. What does the pass record?","workspacePanel":"visualizer","summary":"The queue starts holding just the root.","options":[{"id":"one-avg","label":"[5]: snapshot 1, total 5, divide by 1","rationale":"The snapshot is 1 because the root is the only node, so the total 5 divided by 1 records one average, 5.","isCorrect":true},{"id":"flat-five","label":"5, as a bare number","rationale":"The result is a list of per-depth averages. A single node returns [5], one list entry for one depth.","isCorrect":false},{"id":"empty","label":"An empty list","rationale":"A single real node is one depth, so it contributes one average; the empty list is only for a null root.","isCorrect":false}],"answer":"[5]. The snapshot is 1, the total is 5, and dividing by 1 records the single average.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single","state":{"tree":[5],"node":0}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Code the rule","title":"Build the per-depth average","workspacePanel":"visualizer","ctaLabel":"Start coding","summary":"One snapshot does double duty: it bounds the total and divides it.","body":["Guard the null root, then seed a queue with the root. Each pass snapshots the queue size, totals exactly that many values while enqueueing their children, and divides the total by the snapshot before recording it.","The snapshot gives both how many nodes to total and the count to divide by, so the divisor never drifts to the next depth."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2]}}]}},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the per-depth average","summary":"Now build the sweep: guard the null root, seed the queue with it, then on each depth snapshot the queue size, reset the total, sum exactly that many nodes while their children queue up behind, and divide by the snapshot before recording it; return the averages once the queue empties.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Carry it forward","title":"What to carry forward","workspacePanel":"code","summary":"You averaged each depth with a queue and one size snapshot.","body":["Breadth-first search uses a queue plus discipline about the frontier. The size snapshot taken before each depth gives one clean average per depth because it is both the bound on the total and the divisor."],"takeaways":[{"title":"An average needs a sum and a count","body":"Each depth’s answer is its total over its node count, so both have to come from exactly that depth: 9 and 20 give 29 over 2, which is 14.5."},{"title":"The snapshot is the divisor","body":"Reading the queue size before the depth fixes the count before any child is enqueued, so the same number that bounds the total also divides it."},{"title":"Reset the total once per depth, not per node","body":"Clearing the running total inside the inner loop wipes every node but the last, so depth 1 of [3, 9, 20, null, null, 15, 7] records 20 over 2 as 10 instead of 14.5."},{"title":"One pass avoids re-walks","body":"The BFS sweep is O(n) time because each node is processed once, with O(width) queue space, down from re-walking depths for about n times the height on a one-branch tree."}],"nextAction":"Submit to run your solution against every test. Try Binary Tree Level Order Traversal next, where each depth records its values instead of their average."}],"slidesOrigin":"authored"}}
