{"id":"binary-tree-level-order-traversal-ii","title":"Binary Tree Level Order Traversal II","difficulty":"medium","patterns":["tree-bfs"],"primaryConcept":"tree-bfs-basics","concepts":["tree-bfs-basics"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"tree","primaryParam":"root","sizeMetric":"nodes"},"description":"Given the root of a binary tree, return its level order traversal from bottom to top. Values inside each level should still be ordered from left to right.","examples":[{"input":"root = [3,9,20,null,null,15,7]","output":"[[15,7],[9,20],[3]]","explanation":"Top-down levels are [3], [9,20], [15,7]. Returning bottom-up reverses the level list."},{"input":"root = [1]","output":"[[1]]","explanation":"A single-node tree has one level."}],"constraints":[{"id":"the-number-of-nodes-in-the-tree-is-in-the-range-0-2000","text":"The number of nodes in the tree is in the range [0, 2000]","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":0,"max":2000}},{"id":"1000-node-val-1000","text":"-1000 <= Node.val <= 1000","check":{"kind":"valueRange","target":"root","selector":"treeValues","min":-1000,"max":1000}}],"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 levelOrderBottom(self, root: TreeNode) -> list[list[int]]:\n        # Your code here\n        pass","functionName":"levelOrderBottom","testCases":[{"id":"1","input":{"root":{"val":3,"left":{"val":9,"left":null,"right":null},"right":{"val":20,"left":{"val":15,"left":null,"right":null},"right":{"val":7,"left":null,"right":null}}}},"expected":[[15,7],[9,20],[3]],"description":"Three-level tree."},{"id":"2","input":{"root":{"val":1,"left":null,"right":null}},"expected":[[1]],"description":"Single-node tree."},{"id":"3","input":{"root":null},"expected":[],"description":"Empty tree."},{"id":"4","input":{"root":{"val":1,"left":{"val":2,"left":{"val":4,"left":null,"right":null},"right":null},"right":{"val":3,"left":null,"right":null}}},"expected":[[4],[2,3],[1]],"description":"Unbalanced tree still keeps left-to-right order inside each level."},{"id":"h1","input":{"root":{"val":1,"left":null,"right":{"val":2,"left":null,"right":{"val":3,"left":null,"right":{"val":4,"left":null,"right":null}}}}},"expected":[[4],[3],[2],[1]]},{"id":"h2","input":{"root":{"val":1,"left":{"val":2,"left":{"val":4,"left":null,"right":null},"right":{"val":5,"left":null,"right":null}},"right":{"val":3,"left":{"val":6,"left":null,"right":null},"right":{"val":7,"left":null,"right":null}}}},"expected":[[4,5,6,7],[2,3],[1]]},{"id":"h3","input":{"root":{"val":2,"left":null,"right":{"val":3,"left":{"val":4,"left":null,"right":null},"right":null}}},"expected":[[4],[3],[2]]},{"id":"h4","input":{"root":{"val":5,"left":null,"right":{"val":6,"left":{"val":7,"left":null,"right":null},"right":{"val":8,"left":null,"right":null}}}},"expected":[[7,8],[6],[5]]},{"id":"h5","input":{"root":{"val":0,"left":{"val":-1,"left":{"val":-2,"left":null,"right":null},"right":null},"right":{"val":1,"left":null,"right":{"val":2,"left":null,"right":null}}}},"expected":[[-2,2],[-1,1],[0]]},{"id":"h6","input":{"root":{"val":9,"left":{"val":8,"left":null,"right":null},"right":null}},"expected":[[8],[9]]},{"id":"h7","input":{"root":{"val":1,"left":{"val":1,"left":{"val":1,"left":null,"right":null},"right":null},"right":{"val":1,"left":null,"right":{"val":1,"left":null,"right":null}}}},"expected":[[1,1],[1,1],[1]],"description":"Duplicate values on both sides should not affect bottom-up level grouping."},{"id":"h8","input":{"root":{"val":10,"left":{"val":5,"left":{"val":3,"left":{"val":1,"left":null,"right":null},"right":null},"right":{"val":7,"left":null,"right":null}},"right":{"val":15,"left":null,"right":{"val":18,"left":null,"right":null}}}},"expected":[[1],[3,7,18],[5,15],[10]],"description":"A deeper sparse branch appears alone at the bottom level."}],"hints":[{"level":1,"content":"This is standard level-order traversal, but the final list of levels is reversed."},{"level":2,"content":"Use a queue and capture the current queue width before processing each level."},{"level":3,"content":"Append each level top-down, then `return` the levels in reverse order."}],"guidedFlow":{"progressRevision":"binary-tree-level-order-traversal-ii-2026-07-19-frontier-derivation","version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Pick the traversal that keeps each depth as its own group so the depths can be ordered bottom-up.","approaches":[{"id":"bfs-reverse","name":"Queue sweep, then reverse the depths","summary":"Carry the next depth in a FIFO frontier, collect the depths top-down, then reverse the finished outer list.","decisionReason":"A breadth-first frontier follows the tree one depth at a time while preserving left-to-right discovery. That makes each depth directly available as one output group.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Holds up to one depth's width in the queue, and visits each node once."],"isOptimal":true},{"id":"dfs-depth","name":"DFS with a depth index","summary":"Recurse depth-first with a depth counter, appending each value to the list for its depth, then reverse the depth list.","decisionReason":"Depth-indexed DFS builds the same bottom-up levels in O(n) time. This flow uses a queue because each complete depth appears as one frontier before the outer list is reversed.","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["No explicit queue, but the depth grouping rides on a recursion argument and is harder to reason about."],"isViable":true,"isOptimal":false}]},"codingCheckpoints":[{"id":"check-empty","title":"Handle an empty tree","description":"Return an empty list when root is missing.","commonMistakes":["Trying to enqueue a null root","Returning None instead of an empty list"],"hint":"The output for an empty tree has no levels.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"handles_empty_tree_return","scope":"check-empty","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Short-circuit null root input with an empty level list.","doneWhen":"The implementation checks root before queue initialization and returns [] for a missing root.","shouldFailWhen":"The code dereferences root before checking it or returns a non-list sentinel.","roles":["root","empty result"],"mustProve":["The root is checked for emptiness.","The empty case returns an empty sequence."],"mustNotAccept":["Enqueuing root before a null check.","Returning None or a scalar for the empty tree."],"equivalentVariants":["Use `if not root: return []`.","Use an equivalent null check in another language."],"proofSnippets":[{"id":"py-level-bottom-check-empty","language":"python","code":"class Solution:\n    def levelOrderBottom(self, root: TreeNode) -> list[list[int]]:\n        if not root:\n            return []"}]}},{"id":"init-structures","title":"Initialize result and queue","description":"Create the level result list and seed the queue with the root node.","commonMistakes":["Forgetting to store the result levels","Starting the queue with root.val instead of root"],"hint":"The queue stores nodes, while result stores lists of values.","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 the BFS frontier and the batched level result container.","doneWhen":"A result list exists and a queue/frontier contains the root node before the BFS loop.","shouldFailWhen":"The queue is missing, starts empty, or stores only the root value.","roles":["result levels","BFS queue","root node"],"mustProve":["The result collection is initialized.","The BFS queue is initialized with root."],"mustNotAccept":["Using a stack as the primary frontier.","Storing values in the frontier instead of tree nodes."],"equivalentVariants":["Use a list with a head index.","Use a deque or queue abstraction."],"proofSnippets":[{"id":"py-level-bottom-init-structures","language":"python","code":"class Solution:\n    def levelOrderBottom(self, root: TreeNode) -> list[list[int]]:\n        if not root:\n            return []\n        result = []\n        queue = [root]"}]}},{"id":"level-size","title":"Capture the current level width","description":"Before processing a level, capture how many nodes belong to that level.","commonMistakes":["Letting newly enqueued children extend the current level","Using the total queue length after popping nodes"],"hint":"With a head index, the current level width is the queue size minus the head position.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"captures_bfs_level_boundary","scope":"level-size","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Freeze the number of nodes in the current level before processing it.","doneWhen":"The implementation captures the current frontier width and uses it to bound a per-level loop.","shouldFailWhen":"Children appended during the level can be processed in the same level.","roles":["queue","head index","level size"],"mustProve":["The current level width is computed before the inner loop.","The inner loop is bounded by that width."],"mustNotAccept":["A loop that drains the entire queue as one level.","No per-level boundary capture."],"equivalentVariants":["Capture the number of unread queued nodes when using a head index.","Capture the queue size before removing nodes when using a front-removal queue."],"proofSnippets":[{"id":"py-level-bottom-level-size","language":"python","code":"class Solution:\n    def levelOrderBottom(self, root: TreeNode) -> list[list[int]]:\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 = []\n            for _ in range(level_size):\n                pass"}]}},{"id":"process-level","title":"Collect one level and enqueue children","description":"For each node in the current level, append its value and enqueue any children.","commonMistakes":["Appending child values to the current level","Forgetting one child side"],"hint":"The level list stores current nodes only; child nodes go into the queue for later levels.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"processes_batched_level_nodes","scope":"process-level","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Process exactly the captured level nodes, collect their values, and enqueue existing children.","doneWhen":"The inner loop reads each current node, records node.val in the level list, and appends left/right children when present.","shouldFailWhen":"The loop skips node values, processes children immediately, or misses a child side.","roles":["current node","level values","child enqueue"],"mustProve":["The current node is taken from the BFS frontier.","The node value is appended to the current level.","Existing children are enqueued for later processing."],"mustNotAccept":["Appending child values into the current level.","Dropping left or right child traversal."],"equivalentVariants":["Use a list queue and head index.","Use a deque and popleft."],"proofSnippets":[{"id":"py-level-bottom-process-level","language":"python","code":"class Solution:\n    def levelOrderBottom(self, root: TreeNode) -> list[list[int]]:\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 = []\n            for _ in range(level_size):\n                node = queue[head]\n                head += 1\n                level.append(node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            result.append(level)"}]}},{"id":"return-levels","title":"Return levels from bottom to top","description":"Reverse the collected level list so the deepest level appears first.","commonMistakes":["Reversing values inside each level","Returning top-down level order"],"hint":"Only reverse the outer list of levels.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_batched_level_result","scope":"return-levels","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Return the batched level traversal with the level order inverted bottom-up.","doneWhen":"The function returns a sequence derived from all collected levels, with deepest levels first.","shouldFailWhen":"The function returns only one level, reverses each level's values, or leaves the levels top-down.","roles":["collected levels","bottom-up output"],"mustProve":["The returned value is derived from the batched level result.","The outer level order is reversed for the return."],"mustNotAccept":["Returning current level only.","Reversing the values inside levels instead of the level order."],"equivalentVariants":["Return `result[::-1]`.","Insert each completed level at the front while traversing top-down."],"proofSnippets":[{"id":"py-level-bottom-return-levels","language":"python","code":"class Solution:\n    def levelOrderBottom(self, root: TreeNode) -> list[list[int]]:\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 = []\n            for _ in range(level_size):\n                node = queue[head]\n                head += 1\n                level.append(node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            result.append(level)\n        return result[::-1]"}]}}],"slides":[{"id":"the-task","chapter":"Read the signal","kind":"info","eyebrow":"Read the problem","title":"Return the levels deepest first","workspacePanel":"problem","body":["Level order lists the tree's values one depth at a time, left to right within a depth. This variant returns those depths from the bottom up: the deepest depth first, the root's depth last.","Reversing the order of the depths must leave the values inside each depth in their original left-to-right order."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-task-state","state":{"tree":[3,9,20,null,null,15,7]}}]}},{"id":"queue-meaning","chapter":"The idea","kind":"case-probe","eyebrow":"Find the next unit of work","title":"After visiting 3, which nodes should be carried forward together?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"queue-meaning-s","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2]}}]},"summary":"The root 3 has exposed children 9 and 20, and the answer must keep each depth as one list.","options":[{"id":"frontier","label":"Carry 9 and 20 together as the next depth","rationale":"Both children sit one edge below the root, so they form the next output group. A FIFO frontier can carry that whole depth forward in left-to-right discovery order.","isCorrect":true},{"id":"all","label":"Carry every unvisited node in the tree at once","rationale":"The leaves 15 and 7 are two edges below the root. Bringing them forward now would mix the next depth with a later one.","isCorrect":false},{"id":"values","label":"Follow 9's branch to the bottom before returning to 20","rationale":"Finishing one branch first loses the whole-depth grouping the output asks for. The two siblings must remain in the same unit of work.","isCorrect":false}],"answer":"Carry 9 and 20 together as the next depth. A FIFO queue records that frontier; when a depth begins, the queue contains exactly that depth's nodes."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which approach keeps the next depth together?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"tree":[3,9,20,null,null,15,7],"node":0,"swapped":[1,2]}}]}},{"id":"level-boundary","chapter":"The idea","kind":"case-probe","eyebrow":"Build the state","title":"How do you keep this depth's nodes from mixing with the next?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"level-boundary-s","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2],"swapped":[5,6]}}]},"summary":"The queue held 9 and 20 for this depth; processing them just pushed 15 and 7 onto the same queue, so it now carries two depths at once.","options":[{"id":"snapshot","label":"Record the queue's size now, and process exactly that many nodes","rationale":"The count of nodes waiting right now is this depth's width. Record it, process that many, and every child enqueued meanwhile belongs to the next depth.","isCorrect":true},{"id":"null-marker","label":"Push a null marker behind this depth and stop when you reach it","rationale":"That works but needs a sentinel threaded through the queue. Recording the width up front needs only one integer.","isCorrect":false},{"id":"until-empty","label":"Process until the queue is empty","rationale":"An unbounded pass has no idea where this depth ends, so the count that should define one depth is meaningless. Each pass has to be bounded by the recorded width.","isCorrect":false}],"answer":"Record the queue's size before the depth; that count is exactly how many nodes belong to it."},{"id":"top-down-collected","chapter":"The idea","kind":"case-probe","eyebrow":"Find the gap","title":"The sweep finishes [[3],[9,20],[15,7]] top-down, but the answer is bottom-up. What gets you there?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"top-down-s","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2,5,6]}}]},"summary":"The collected list is [[3], [9, 20], [15, 7]].","options":[{"id":"reverse-levels","label":"Reverse the finished list of depths so the deepest comes first","rationale":"The depths are already collected correctly, just in the wrong order, so a single reversal of the depth list flips top-down into bottom-up.","isCorrect":true},{"id":"collect-leaf-first","label":"Run the sweep so it reaches leaves before the root","rationale":"A queue always discovers the root before its descendants; you cannot make BFS visit a depth before the one above it.","isCorrect":false},{"id":"sort-by-depth","label":"Sort the depths by their values","rationale":"Ordering is by depth, not by value, so sorting would scramble depths that happen to share or cross values.","isCorrect":false}],"answer":"Collect the depths top-down, then reverse the list of depths so the deepest depth comes first."},{"id":"reverse-which","chapter":"The idea","kind":"case-probe","eyebrow":"Protect the invariant","title":"What must stay unchanged when the depths reverse?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"reverse-which-s","state":{"tree":[3,9,20,null,null,15,7],"swapped":[5,6],"visited":[0,1,2]}}]},"summary":"Compare the collected [[3], [9, 20], [15, 7]] with the required [[15, 7], [9, 20], [3]].","options":[{"id":"outer","label":"Each depth's values must remain in left-to-right order","rationale":"The deepest group moves from last to first, yet [15, 7] must remain [15, 7]. Only the positions of the depth lists change.","isCorrect":true},{"id":"inner","label":"The root's depth must remain first","rationale":"Bottom-up order moves the root's depth to the end. Its value stays unchanged, but its depth list changes position.","isCorrect":false},{"id":"both","label":"Every node's index in the outer result must remain fixed","rationale":"The outer positions are exactly what must change: the deepest depth moves first and the root depth moves last.","isCorrect":false}],"answer":"Keep the values inside each depth in left-to-right order. Reverse only the outer list, so [15, 7] moves intact to the front."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Set up the sweep","title":"Sweep top-down, then flip the depths","workspacePanel":"visualizer","body":["Seed the queue with the root. Each pass locks in the queue width, records that many values into one fresh depth list, and enqueues their children for the next pass.","The depths come out top-down: [3], then [9, 20], then [15, 7]. Reversing that finished list of depths is the last move, and it leaves the values inside each depth alone.","Watch the three depths fill on [3, 9, 20, null, null, 15, 7], then predict what the reversal does to the outer list."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"tree":[3,9,20,null,null,15,7],"visited":[0]}}]}},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the sweep","title":"Sweep three depths, then reverse","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"b-root","state":{"tree":[3,9,20,null,null,15,7],"node":0}},{"id":"b-depth2","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2]}},{"id":"b-depth3","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2],"swapped":[5,6]}},{"id":"b-reverse","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2,5,6]}}]},"beats":[{"id":"b-root","title":"Depth one holds only the root. What does this pass produce?","summary":"The queue holds just 3, so the width is one.","prompt":"You snapshot the width, then process exactly that many nodes.","options":[{"id":"record-3","label":"Record [3] as the first depth and enqueue 9 and 20","rationale":"One node at this depth means the list [3] is complete, and its children join the queue for the next pass.","isCorrect":true},{"id":"record-children","label":"Record [3, 9, 20] together","rationale":"9 and 20 are a depth below; they go to the queue, not into the root's depth list.","isCorrect":false},{"id":"skip","label":"Skip the root since the answer is bottom-up","rationale":"Every depth is collected, including the root's. The flip to bottom-up happens once, at the end.","isCorrect":false}],"answer":"Record [3] and enqueue 9 and 20; the result so far is [[3]]."},{"id":"b-depth2","title":"Depth two holds 9 then 20. Where do 20's children 15 and 7 go?","summary":"The width was snapshotted at two before this pass began.","prompt":"You process 9, then 20, recording into one list.","options":[{"id":"back","label":"To the back of the queue, for the next depth","rationale":"The width was already fixed at two, so 15 and 7 wait behind the snapshot and form the next depth.","isCorrect":true},{"id":"this-level","label":"Into this depth's list, after 9 and 20","rationale":"15 and 7 sit a depth below 9 and 20; recording them here would merge two depths into one list.","isCorrect":false},{"id":"now","label":"Processed immediately, right after 20","rationale":"Processing them now interleaves the depths. They are enqueued and the bounded pass finishes first.","isCorrect":false}],"answer":"To the back of the queue. This depth records [9, 20]; the result is [[3], [9, 20]]."},{"id":"b-depth3","title":"Depth three holds the last two leaves. What does this depth record?","summary":"The queue width is two; the two leaves 15 and 7 are queued for this depth.","prompt":"You process this depth's nodes in queue order, then the queue empties.","options":[{"id":"left-right","label":"[15, 7], in the order they were processed","rationale":"Left to right, 15 comes before 7, so the depth records [15, 7] and the queue empties after. The result is [[3], [9, 20], [15, 7]].","isCorrect":true},{"id":"right-left","label":"[7, 15], already flipped for the bottom-up answer","rationale":"The within-depth order stays left to right. The bottom-up flip reorders depths, never the values inside one.","isCorrect":false},{"id":"merge","label":"Nothing new, the sweep is already done","rationale":"15 and 7 are still queued, so this depth must be recorded before the queue empties.","isCorrect":false}],"answer":"[15, 7], left to right. The full top-down result is [[3], [9, 20], [15, 7]]."},{"id":"b-reverse","title":"The depths are [[3], [9, 20], [15, 7]]. What does reversing the outer list return?","summary":"The sweep is finished and the depths are in top-down order.","prompt":"You flip only the outer list, leaving each depth's values in place.","options":[{"id":"bottom-up","label":"[[15, 7], [9, 20], [3]]","rationale":"The deepest depth moves first and the root's depth last, while [15, 7] stays [15, 7]. That is the required bottom-up answer.","isCorrect":true},{"id":"values-flipped","label":"[[7, 15], [20, 9], [3]]","rationale":"That flips the values inside each depth as well. Only the outer list reverses; the within-depth order is untouched.","isCorrect":false},{"id":"unchanged","label":"[[3], [9, 20], [15, 7]], unchanged","rationale":"That is the top-down order. Reversing the outer list is what makes the result bottom-up.","isCorrect":false}],"answer":"[[15, 7], [9, 20], [3]]: the depths flip, each depth's left-to-right order stays."}]},{"id":"reverse-values-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could you read the level width after popping the first node instead?","workspacePanel":"trace","summary":"It looks tidier to pull the head node, enqueue its children, and then measure the width for the rest of the pass. Each pass still starts a fresh depth and the count is a real number. But by the time you measure, the head has advanced and its children already sit in the queue, so the width comes out wrong. Watch a depth absorb part of the one below it.","pitfall":"The code below measures level_size after reading the head and appending its children. The snapshot is taken too late, so the count folds the next depth's first nodes into this pass.","whyItMatters":"Snapshot len(queue) BEFORE the pass pops or appends anything. Measured after the head advances and its children are enqueued, the width counts nodes from the next depth, so a depth absorbs part of the level below and the grouping is wrong before any reverse can help.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\nqueue = [root]\nhead = 0\nwhile head < len(queue):\n    node = queue[head]\n    head += 1\n    if node.left:\n        queue.append(node.left)\n    if node.right:\n        queue.append(node.right)\n    level_size = len(queue) - head\n    level = [node.val]\n    for _ in range(level_size):\n        node = queue[head]\n        head += 1\n        level.append(node.val)\n        if node.left:\n            queue.append(node.left)\n        if node.right:\n            queue.append(node.right)\n    result.append(level)\nreturn result","steps":[{"id":"pit-snapshot-late","title":"The head is read and its children queued before the width is measured","codeLine":11,"summary":"The pass reads 3, advances past it, and enqueues 9 and 20. Only now is level_size measured, as len(queue) - head, which is 3 - 1 = 2. The count already reflects the next depth's nodes sitting in the queue.","state":{"tree":[3,9,20,null,null,15,7],"node":0,"swapped":[1,2]}},{"id":"pit-absorb","title":"A width of two pulls 9 and 20 into the root's depth","codeLine":16,"summary":"level already holds 3, and the inner loop runs twice. It reads 9, then 20, appending both into that same list. The root's depth is now [3, 9, 20].","state":{"tree":[3,9,20,null,null,15,7],"node":2,"visited":[0]}},{"id":"pit-bleed","title":"Processing 20 queues 15 and 7 as the next depth","codeLine":21,"summary":"20's children 15 and 7 join the queue, and this pass closes with result holding [[3, 9, 20]]. Values 9 and 20 were queued for the second depth but got appended beside root 3.","state":{"tree":[3,9,20,null,null,15,7],"swapped":[5,6],"visited":[0,1,2]}},{"id":"pit-wrong","title":"The depths no longer line up with the tree","codeLine":22,"summary":"The sweep returns [[3, 9, 20], [15, 7]]: the root's depth swallowed all of depth two, so the grouping is wrong before any reverse runs. Snapshotting the width before the pass keeps each depth its own list.","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2,5,6]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nconst queue = [root];\nlet head = 0;\nwhile (head < queue.length) {\n    let node = queue[head];\n    head++;\n    if (node.left) {\n        queue.push(node.left);\n    }\n    if (node.right) {\n        queue.push(node.right);\n    }\n    const levelSize = queue.length - head;\n    const level = [node.val];\n    for (let i = 0; i < levelSize; i++) {\n        node = queue[head];\n        head++;\n        level.push(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(level);\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":19,"18":20,"19":22,"20":23,"21":26,"22":28},"statementBundles":{"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"18":{"startLine":20,"endLine":21},"20":{"startLine":23,"endLine":25},"21":{"startLine":26,"endLine":27}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<Array<number>> = [];\nconst queue = [root];\nlet head = 0;\nwhile (head < queue.length) {\n    let node = queue[head];\n    head++;\n    if (node.left) {\n        queue.push(node.left);\n    }\n    if (node.right) {\n        queue.push(node.right);\n    }\n    const levelSize = queue.length - head;\n    const level = [node.val];\n    for (let i = 0; i < levelSize; i++) {\n        node = queue[head];\n        head++;\n        level.push(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(level);\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":19,"18":20,"19":22,"20":23,"21":26,"22":28},"statementBundles":{"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"18":{"startLine":20,"endLine":21},"20":{"startLine":23,"endLine":25},"21":{"startLine":26,"endLine":27}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> result = new ArrayList<>();\nList<TreeNode> queue = new ArrayList<>(List.of(root));\nint head = 0;\nwhile (head < queue.size()) {\n    TreeNode node = queue.get(head);\n    head++;\n    if (node.left != null) {\n        queue.add(node.left);\n    }\n    if (node.right != null) {\n        queue.add(node.right);\n    }\n    int levelSize = queue.size() - head;\n    List<Integer> level = new ArrayList<>(List.of(node.val));\n    for (int i = 0; i < levelSize; i++) {\n        node = queue.get(head);\n        head++;\n        level.add(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(level);\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":19,"18":20,"19":22,"20":23,"21":26,"22":28},"statementBundles":{"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"18":{"startLine":20,"endLine":21},"20":{"startLine":23,"endLine":25},"21":{"startLine":26,"endLine":27}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> result = new();\nList<TreeNode> queue = new() { root };\nint head = 0;\nwhile (head < queue.Count) {\n    TreeNode node = queue[head];\n    head++;\n    if (node.left != null) {\n        queue.Add(node.left);\n    }\n    if (node.right != null) {\n        queue.Add(node.right);\n    }\n    int levelSize = queue.Count - head;\n    List<int> level = new() { node.val };\n    for (int i = 0; i < levelSize; i++) {\n        node = queue[head];\n        head++;\n        level.Add(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(level);\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":19,"18":20,"19":22,"20":23,"21":26,"22":28},"statementBundles":{"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"18":{"startLine":20,"endLine":21},"20":{"startLine":23,"endLine":25},"21":{"startLine":26,"endLine":27}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> result;\nvector<TreeNode*> queue{root};\nsize_t head = 0;\nwhile (head < queue.size()) {\n    TreeNode* node = queue[static_cast<int>(head)];\n    head++;\n    if (node->left) {\n        queue.push_back(node->left);\n    }\n    if (node->right) {\n        queue.push_back(node->right);\n    }\n    int level_size = queue.size() - head;\n    vector<int> level{node->val};\n    for (int i = 0; i < level_size; i++) {\n        node = queue[static_cast<int>(head)];\n        head++;\n        level.push_back(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(level);\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":19,"18":20,"19":22,"20":23,"21":26,"22":28},"statementBundles":{"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"18":{"startLine":20,"endLine":21},"20":{"startLine":23,"endLine":25},"21":{"startLine":26,"endLine":27}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","ctaLabel":"Check edge cases","workspacePanel":"visualizer","body":["The depth boundary held the sweep together, and the final reverse only touched the outer list of depths.","Now push on the shape. An empty tree gives the sweep no root to seed the queue. A single node gives the sweep just one depth to collect."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"tree":[3,9,20,null,null,15,7],"node":0}}]}},{"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":{"tree":[]}}]},"summary":"The input is null: there is no root, so the queue has nothing to seed.","options":[{"id":"empty-list","label":"An empty list, before the queue is ever built","rationale":"No nodes means no depths to collect and nothing to reverse. Guard the null root up front and return an empty list.","isCorrect":true},{"id":"list-of-empty","label":"A list holding one empty level","rationale":"There is no depth at all, so the answer holds zero levels, not one empty level.","isCorrect":false},{"id":"crash","label":"It is fine to seed the queue with the null root","rationale":"Reading a value off a null root fails. The guard has to come before any queue work.","isCorrect":false}],"answer":"Guard the null root first and return an empty list, before the queue is built."},{"id":"edge-single","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does a one-node tree return after the bottom-up reverse?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-single-state","state":{"tree":[1],"node":0}}]},"summary":"The tree is a single node 1, so the sweep collects exactly one depth.","options":[{"id":"single-level","label":"[[1]], because reversing a one-level list leaves it the same","rationale":"The sweep records [[1]] top-down, and reversing a list with one depth returns the same list, so the answer is [[1]].","isCorrect":true},{"id":"flat","label":"[1], a flat list of values","rationale":"The answer groups values by depth, so even one depth is wrapped in its own list: [[1]], not [1].","isCorrect":false},{"id":"empty","label":"[], because there is nothing below the root to reverse with","rationale":"One node is still one depth, which is recorded and returned. The reverse having nothing to reorder does not drop the depth.","isCorrect":false}],"answer":"[[1]]. One depth is collected and reversing a single-level list returns it unchanged."},{"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":"Watch one thing at the end: reverse the outer list of depths, never the values inside a depth.","body":["Guard the empty tree, seed a queue with the root, and sweep while it holds nodes. Each pass: lock in the current width, record that many values left to right into one fresh depth, and enqueue their children for the next pass.","When the queue empties you have the depths top-down. Reverse that finished list of depths so the deepest comes first, and return it."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"tree":[3,9,20,null,null,15,7],"node":0,"swapped":[1,2]}}]}},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the bottom-up sweep","summary":"Now turn the sweep into code: guard the empty tree, seed the result and a queue with the root, then on each pass lock in the current width, record that many values into one depth and enqueue their children, and finally reverse the finished list of depths.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Carry it forward","title":"What to carry forward","summary":"You swept the tree into top-down depths, then flipped the outer list to read bottom-up.","workspacePanel":"code","body":["Bottom-up level order is plain breadth-first search with one extra move at the end. The width snapshot groups nodes into depths, and reversing the finished list of depths reorders them without disturbing the left-to-right order inside any depth."],"takeaways":[{"title":"The width snapshot makes the depths","body":"Lock in the queue length before a pass and process exactly that many nodes, so children enqueued meanwhile wait for the next depth."},{"title":"Reverse the outer depth list","body":"The sweep collects depths top-down and left-to-right. Reversing only the outer list gives the deepest depth first while [15, 7] stays [15, 7]."},{"title":"O(n) time and space","body":"Each node is recorded once and the queue holds at most one depth's width, so the sweep plus the single reverse is linear."}],"nextAction":"Submit your solution to run it against every test case."}],"slidesOrigin":"authored"}}
