{"id":"binary-tree-zigzag-level-order-traversal","title":"Binary Tree Zigzag Level Order Traversal","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","syntheticTestConfig":{"inputShape":"tree","primaryParam":"root","sizeMetric":"tree-nodes","sizes":[7,15,31,63],"constraints":["binary-tree"]},"description":"Given the root of a binary tree, return its zigzag level order traversal.\n\nThe first level is read from left to right, the next level from right to left, and the direction alternates on every level.","examples":[{"input":"root = [3,9,20,null,null,15,7]","output":"[[3],[20,9],[15,7]]","explanation":"The second level is reversed, while the third level is read left to right again."},{"input":"root = [1]","output":"[[1]]","explanation":"A single node has one left-to-right level."}],"constraints":[{"id":"0-number-of-nodes-2000","text":"0 <= number of nodes <= 2000","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":0,"max":2000}},{"id":"100-node-val-100","text":"-100 <= node.val <= 100","check":{"kind":"valueRange","target":"root","selector":"treeValues","min":-100,"max":100}}],"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 zigzagLevelOrder(self, root: TreeNode) -> list[list[int]]:\n        # Your code here\n        pass","functionName":"zigzagLevelOrder","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],[20,9],[15,7]],"description":"Canonical three-level zigzag sample."},{"id":"2","input":{"root":{"val":1,"left":null,"right":null,"__id__":"tree-0"}},"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,"__id__":"tree-3"},"right":null,"__id__":"tree-1"},"right":{"val":3,"left":null,"right":{"val":5,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[[1],[3,2],[4,5]],"description":"Sparse tree with reversal on the second level."},{"id":"5","input":{"root":{"val":1,"left":{"val":2,"left":{"val":3,"left":null,"right":null,"__id__":"tree-2"},"right":null,"__id__":"tree-1"},"right":null,"__id__":"tree-0"}},"expected":[[1],[2],[3]],"description":"Skewed tree where each level has one node."},{"id":"6","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],[3,2],[4,5,6,7]],"description":"Complete tree with alternating level direction."},{"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,"__id__":"tree-3"},"__id__":"tree-2"},"__id__":"tree-1"},"__id__":"tree-0"}},"expected":[[1],[2],[3],[4]],"description":"A right-skewed tree keeps one node per level."},{"id":"h2","input":{"root":{"val":1,"left":{"val":2,"left":null,"right":{"val":4,"left":{"val":6,"left":null,"right":null,"__id__":"tree-5"},"right":null,"__id__":"tree-3"},"__id__":"tree-1"},"right":{"val":3,"left":{"val":5,"left":null,"right":{"val":7,"left":null,"right":null,"__id__":"tree-6"},"__id__":"tree-4"},"right":null,"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[[1],[3,2],[4,5],[7,6]],"description":"Mixed branching still reverses every other level."},{"id":"h3","input":{"root":{"val":1,"left":{"val":2,"left":{"val":4,"left":{"val":7,"left":null,"right":null,"__id__":"tree-7"},"right":null,"__id__":"tree-3"},"right":{"val":5,"left":null,"right":{"val":8,"left":null,"right":null,"__id__":"tree-8"},"__id__":"tree-4"},"__id__":"tree-1"},"right":{"val":3,"left":null,"right":{"val":6,"left":{"val":9,"left":null,"right":null,"__id__":"tree-9"},"right":null,"__id__":"tree-5"},"__id__":"tree-2"},"__id__":"tree-0"}},"expected":[[1],[3,2],[4,5,6],[9,8,7]],"description":"A wider fourth level still alternates cleanly."},{"id":"h4","input":{"root":{"val":1,"left":{"val":2,"left":{"val":3,"left":null,"right":{"val":5,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-2"},"right":{"val":4,"left":{"val":6,"left":null,"right":null,"__id__":"tree-5"},"right":null,"__id__":"tree-3"},"__id__":"tree-1"},"right":null,"__id__":"tree-0"}},"expected":[[1],[2],[3,4],[6,5]],"description":"Uneven children still preserve the zigzag order."},{"id":"zero-and-negative-values","input":{"root":{"__type__":"TreeNode","val":0,"left":{"__type__":"TreeNode","val":-2,"left":{"__type__":"TreeNode","val":-4,"left":null,"right":null},"right":null},"right":{"__type__":"TreeNode","val":3,"left":{"__type__":"TreeNode","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","val":-1,"left":null,"right":null}}}},"expected":[[0],[3,-2],[-4,1,-1]],"description":"Zigzag traversal keeps signed node values while alternating level direction."},{"id":"h5","input":{"root":{"val":10,"left":{"val":5,"left":null,"right":{"val":7,"left":{"val":6,"left":null,"right":null},"right":null}},"right":{"val":15,"left":{"val":12,"left":null,"right":{"val":13,"left":null,"right":null}},"right":null}}},"expected":[[10],[15,5],[7,12],[13,6]],"description":"Sparse fourth-level nodes are still emitted in the reversed level order."}],"hints":[{"level":1,"content":"Use BFS to process one level at a time."},{"level":2,"content":"Keep a boolean direction flag that flips after each level."},{"level":3,"content":"Collect the level left-to-right, then reverse it when the current direction is right-to-left."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Pick the traversal that keeps each depth whole and reorders it without disturbing how the next depth fans out.","approaches":[{"id":"bfs-reverse-values","name":"Queue sweep, reverse alternate value lists","summary":"Seed a queue with the root. Each pass records how many nodes are waiting, reads exactly that many values left to right into one list, and enqueues their children. Reverse that list on alternate depths.","decisionReason":"Recording how many nodes are waiting groups them by depth in one linear pass, and reversing only the values a depth collected leaves the queue and the next depth untouched.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Holds up to one depth in the queue, visits each node once, and reverses at most n values total."],"isOptimal":true},{"id":"bfs-flip-enqueue","name":"Flip the child enqueue order each level","summary":"Run the queue sweep but, on right-to-left levels, enqueue right child before left so the order is meant to fall out of the queue itself.","decisionReason":"Flipping how children enter the queue changes the positions of the next depth, so the alternation corrupts the level below instead of staying inside the current one.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Same cost, but the direction leaks into the next depth instead of staying local to the current one."],"isOptimal":false}]},"codingCheckpoints":[{"id":"check-empty","title":"Handle an empty tree","description":"Return an empty list when the root is missing.","commonMistakes":["Seeding the queue with a null root","Returning a level that contains a null"],"hint":"No root means no levels.","semanticSpec":{"intent":"Short-circuit an empty tree with an empty level result.","doneWhen":"The code checks for a missing root and returns `[]`.","shouldFailWhen":"This step should fail if null root can enter the queue.","roles":["root","empty result"],"mustProve":["The code returns an empty result for a missing root."],"mustNotAccept":["Returning a level containing null."],"equivalentVariants":["Use `if not root` or an equivalent null check."],"proofSnippets":[{"id":"py-zigzag-check-empty","language":"python","code":"class Solution:\n    def zigzagLevelOrder(self, root: TreeNode) -> list[list[int]]:\n        if not root:\n            return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"handles_empty_tree_return","scope":"check-empty","readMode":"tree-value-query-v1"}]}},{"id":"init-structures","title":"Initialize the sweep","description":"Create the result list, seed the queue with the root, and start the direction at left-to-right.","commonMistakes":["Seeding the queue with the children instead of the root","Starting the direction flag so the first level reverses"],"hint":"The first level holds the root and reads left to right.","semanticSpec":{"intent":"Initialize the BFS queue and output collection.","doneWhen":"The code initializes result state and a queue/frontier containing the root.","shouldFailWhen":"This step should fail if the root is not used as the initial frontier.","roles":["result","queue","root"],"mustProve":["The root is placed in BFS frontier state.","A result collection is initialized."],"mustNotAccept":["Starting from only one child.","Using a stack-only traversal."],"equivalentVariants":["Use a deque or an array plus head pointer."],"proofSnippets":[{"id":"py-zigzag-init-structures","language":"python","code":"from collections import deque\n\nclass Solution:\n    def zigzagLevelOrder(self, root: TreeNode) -> list[list[int]]:\n        if not root:\n            return []\n        result = []\n        queue = deque([root])\n        return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_bfs_result_and_queue","scope":"init-structures","readMode":"tree-value-query-v1"}]}},{"id":"level-size","title":"Capture the level width","description":"Record how many nodes belong to this depth before any child is enqueued.","commonMistakes":["Reading the queue's size after children are added","Letting the inner loop drain the whole queue"],"hint":"Take the width before the pass appends anything.","semanticSpec":{"intent":"Capture a stable BFS level boundary.","doneWhen":"The code stores the current level size before the inner loop processes that level.","shouldFailWhen":"This step should fail if children can extend the current level loop.","roles":["queue","level size","current level"],"mustProve":["A stable level width is captured before child enqueue operations."],"mustNotAccept":["Looping directly over a queue while appending children without a level boundary."],"equivalentVariants":["Use `len(queue)` with pop semantics or `len(queue) - head` with a head pointer."],"proofSnippets":[{"id":"py-zigzag-level-size","language":"python","code":"from collections import deque\n\nclass Solution:\n    def zigzagLevelOrder(self, root: TreeNode) -> list[list[int]]:\n        if not root:\n            return []\n        result = []\n        queue = deque([root])\n        while queue:\n            level_size = len(queue)\n            break\n        return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"captures_bfs_level_boundary","scope":"level-size","readMode":"tree-value-query-v1"}]}},{"id":"process-level","title":"Collect one level left to right","description":"Read each node in this depth, record its value left to right, and enqueue its children in the usual left-then-right order.","commonMistakes":["Recording node objects instead of their values","Flipping the child enqueue order to chase the zigzag"],"hint":"Always enqueue left child then right child; the direction is handled after the level is collected.","semanticSpec":{"intent":"Consume the current BFS level and build the level value list.","doneWhen":"The code processes each node in the level, appends node values, and enqueues existing children.","shouldFailWhen":"This step should fail if child links are not explored or values are not collected.","roles":["current node","level values","left child","right child"],"mustProve":["The code appends current node values to level output.","The code enqueues left and right children when present."],"mustNotAccept":["Processing only one node per level.","Dropping right children."],"equivalentVariants":["Use deque pops or array indexing with a head pointer."],"proofSnippets":[{"id":"py-zigzag-process-level","language":"python","code":"from collections import deque\n\nclass Solution:\n    def zigzagLevelOrder(self, root: TreeNode) -> list[list[int]]:\n        if not root:\n            return []\n        result = []\n        queue = deque([root])\n        while queue:\n            level_size = len(queue)\n            level = []\n            for _ in range(level_size):\n                node = queue.popleft()\n                level.append(node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            break\n        return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"processes_batched_level_nodes","scope":"process-level","readMode":"tree-value-query-v1"}]}},{"id":"return-levels","title":"Reverse alternate levels and return","description":"Reverse the recorded value list when the direction is right-to-left, append it, flip the direction, and return all levels.","commonMistakes":["Forgetting to flip the direction after a level","Reversing every level instead of every other one"],"hint":"Reverse the level list only when the flag points right to left, then toggle the flag.","semanticSpec":{"intent":"Emit each processed BFS level and return the batched level result.","doneWhen":"The code appends each completed level to the result and returns the result.","shouldFailWhen":"This step should fail if completed levels are not accumulated or the final result is not returned.","roles":["level output","direction flag","batched result"],"mustProve":["The code appends completed level outputs to the result.","The function returns the batched level result."],"mustNotAccept":["Returning the queue.","Returning only the last level."],"equivalentVariants":["Reverse alternate levels before appending, or use front insertion while building right-to-left levels."],"proofSnippets":[{"id":"py-zigzag-return-levels","language":"python","code":"from collections import deque\n\nclass Solution:\n    def zigzagLevelOrder(self, root: TreeNode) -> list[list[int]]:\n        if not root:\n            return []\n        result = []\n        queue = deque([root])\n        left_to_right = True\n        while queue:\n            level_size = len(queue)\n            level = []\n            for _ in range(level_size):\n                node = queue.popleft()\n                level.append(node.val)\n                if node.left:\n                    queue.append(node.left)\n                if node.right:\n                    queue.append(node.right)\n            if not left_to_right:\n                level.reverse()\n            result.append(level)\n            left_to_right = not left_to_right\n        return result"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_batched_level_result","scope":"return-levels","readMode":"tree-value-query-v1"}]}}],"slides":[{"id":"the-task","chapter":"Read the signal","kind":"info","eyebrow":"Read the problem","title":"Read each level in a zigzag","workspacePanel":"problem","body":["You are given the root of a binary tree and must return its values grouped by depth, with the reading direction alternating: the first depth left to right, the next right to left, and back again on every depth after that.","The obvious first cut handles the depths one at a time: gather every node at depth 0, then every node at depth 1, and so on, flipping the ones that read backward."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-task-state","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":"Start naive","title":"The version you would write first","summary":"Taking the depths one at a time gets every level right, and it is the first thing most people reach for. Watch how much of the tree each deeper pass has to retrace to get there.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\ndepth = 0\nleft_to_right = True\nwhile True:\n    level = nodes_at_depth(root, depth)\n    if len(level) == 0:\n        break\n    if not left_to_right:\n        level.reverse()\n    result.append(level)\n    left_to_right = not left_to_right\n    depth += 1\nreturn result","typeContext":{"externalFunctions":{"nodes_at_depth":{"params":[{"kind":"class","name":"TreeNode"},"int"],"returns":{"kind":"list","item":"int"}}}},"steps":[{"id":"walk-depth0","codeLine":5,"title":"Depth 0 walks 1 node","summary":"nodes_at_depth starts at the root every time it is called. For depth 0 it stops there and keeps 3.","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[0]}},{"id":"walk-depth1","codeLine":5,"title":"Depth 1 walks 3 nodes to collect 2","summary":"The walk starts at the root again and descends past 3 to reach 9 and 20. The root has now been walked twice.","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2],"swapped":[1,2]}},{"id":"reverse-depth1","codeLine":8,"title":"Depth 1 is the backward one","summary":"The direction is right to left here, so [9, 20] is recorded as [20, 9].","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2],"swapped":[1,2]}},{"id":"walk-depth2","codeLine":5,"title":"Depth 2 walks 5 nodes to collect 2","summary":"Starting from the root a third time, the walk goes down through 9, then back up and down through 20, before reaching 15 and 7. Three of those five nodes were already read on earlier passes.","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2,5,6],"swapped":[5,6]}},{"id":"walk-depth3","codeLine":5,"title":"Depth 3 walks all 5 and collects nothing","summary":"There is no depth 3, but the only way to find that out is to walk the whole tree once more and come back with nothing. An entire pass over the tree buys one empty 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 = [];\nlet depth = 0;\nlet leftToRight = true;\nwhile (true) {\n    const level = nodesAtDepth(root, depth);\n    if (level.length === 0) {\n        break;\n    }\n    if (!leftToRight) {\n        level.reverse();\n    }\n    result.push(level);\n    leftToRight = !leftToRight;\n    depth++;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":12,"11":13,"12":14,"13":16},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":11},"12":{"startLine":14,"endLine":15}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<Array<number>> = [];\nlet depth = 0;\nlet leftToRight = true;\nwhile (true) {\n    const level = nodesAtDepth(root, depth);\n    if (level.length === 0) {\n        break;\n    }\n    if (!leftToRight) {\n        level.reverse();\n    }\n    result.push(level);\n    leftToRight = !leftToRight;\n    depth++;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":12,"11":13,"12":14,"13":16},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":11},"12":{"startLine":14,"endLine":15}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> result = new ArrayList<>();\nint depth = 0;\nboolean leftToRight = true;\nwhile (true) {\n    List<Integer> level = nodesAtDepth(root, depth);\n    if (level.isEmpty()) {\n        break;\n    }\n    if (!leftToRight) {\n        Collections.reverse(level);\n    }\n    result.add(level);\n    leftToRight = !leftToRight;\n    depth++;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":12,"11":13,"12":14,"13":16},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":11},"12":{"startLine":14,"endLine":15}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> result = new();\nint depth = 0;\nbool leftToRight = true;\nwhile (true) {\n    List<int> level = NodesAtDepth(root, depth);\n    if (level.Count == 0) {\n        break;\n    }\n    if (!leftToRight) {\n        level.Reverse();\n    }\n    result.Add(level);\n    leftToRight = !leftToRight;\n    depth++;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":12,"11":13,"12":14,"13":16},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":11},"12":{"startLine":14,"endLine":15}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> result;\nint depth = 0;\nbool left_to_right = true;\nwhile (true) {\n    vector<int> level = nodes_at_depth(root, depth);\n    if (level.empty()) {\n        break;\n    }\n    if (!left_to_right) {\n        reverse(level.begin(), level.end());\n    }\n    result.push_back(level);\n    left_to_right = !left_to_right;\n    depth++;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":12,"11":13,"12":14,"13":16},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":11},"12":{"startLine":14,"endLine":15}}}}}},{"id":"rescan-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Count the work","title":"How much work do the repeated walks add up to?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rescan-cost-s","state":{"tree":[1,2,null,3,null,null,null,4],"node":7,"visited":[0,1,3]}}]},"summary":"Take a worse shape than the sample tree: one long branch, 1 over 2 over 3 over 4. Every depth still starts its walk at the root, so reaching the deepest node re-walks everything above it.","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 read once","rationale":"Each node is recorded once, but reaching a node at depth d re-descends past every shallower node first, so the tree is traversed once per depth rather than once in total.","isCorrect":false},{"id":"constant-extra","label":"A constant amount of extra work per depth","rationale":"A pass for depth d walks every node down to that depth, so deeper passes cost more. On a skewed tree the last pass alone nearly retraces the whole thing.","isCorrect":false}],"answer":"Re-descending for every depth costs about n times the height. Those repeated walks through the upper nodes are the waste worth removing, since each node only needs to be touched once."},{"id":"carry-forward","chapter":"The idea","kind":"case-probe","eyebrow":"Find the state","title":"What could you keep so the next depth is already in hand?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"carry-forward-s","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2],"arrays":[{"name":"children exposed while reading 3","values":[9,20]}]}}]},"summary":"Reading 3 already exposes its children 9 and 20. Those two nodes are exactly the next depth, but the naive version throws that discovery away and starts over at the root.","options":[{"id":"children-frontier","label":"Keep those exposed children in a waiting line, then read the next depth straight from it","rationale":"Reading a node already reveals its children. Park them in a queue as you go, and the next depth is already in hand: no re-descent from the root.","isCorrect":true},{"id":"depth-numbers","label":"Remember each node's depth number and group by it at the end","rationale":"Tagging depths still needs a walk to assign them and a grouping pass afterward, and it never removes the repeated descents.","isCorrect":false},{"id":"recorded-values","label":"Keep the values already recorded so far","rationale":"Recorded values are the answer being built; they say nothing about which nodes come next. The uncovered children are the state that carries forward.","isCorrect":false}],"answer":"Keep the children you uncover in a queue. The next depth is read straight from it, so no depth is ever rediscovered."},{"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],"arrays":[{"name":"queue","values":[9,20,15,7]}]}}]},"summary":"The root has been read, so the queue holds 9 and 20: exactly this depth. Reading them pushes 15 and 7 onto the same queue, which now carries two depths at once.","options":[{"id":"snapshot","label":"Record the queue's size now, and read exactly that many nodes","rationale":"The count of nodes waiting right now is this depth's width. Record it, read 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":"A sentinel node works, but it has to be threaded through the queue and checked for on every pop. The count of nodes already waiting is one integer and needs neither.","isCorrect":false},{"id":"until-empty","label":"Read until the queue is empty","rationale":"An unbounded pass has no idea where this depth ends, so the nodes enqueued during it get read as though they belonged to it.","isCorrect":false}],"answer":"Record the queue's size before the depth; that count is exactly how many nodes belong to it."},{"id":"direction-rule","chapter":"The idea","kind":"case-probe","eyebrow":"Find the rule","title":"The second depth reads right to left. Where should the flip happen?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"direction-rule-s","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2],"arrays":[{"name":"queue","values":[9,20]},{"name":"level","values":[9,20]}]}}]},"summary":"This depth holds 9 then 20 in the queue.","options":[{"id":"reverse-values","label":"Collect [9, 20] left to right, then reverse those values to [20, 9]","rationale":"Reading stays in queue order and children still enqueue left then right, so neither the traversal nor the depth grouping changes. Only this depth's list of values comes out flipped, and that is the whole zigzag.","isCorrect":true},{"id":"flip-enqueue","label":"Enqueue 20's children right child first so the order falls out of the queue","rationale":"Changing how children enter the queue reorders the next depth, not this one. The flip leaks one level down instead of staying local.","isCorrect":false},{"id":"read-backward","label":"Read this depth's nodes from the back of the queue","rationale":"Reading from the back breaks the level boundary, since the back of the queue already holds the next depth's nodes once children are enqueued.","isCorrect":false}],"answer":"Collect the depth left to right, then reverse the values you collected when the direction is right to left. Only that list changes; the sweep and the grouping stay where they are."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Set up the sweep","title":"Sweep each depth, flip alternate lists","workspacePanel":"visualizer","body":["Seed the queue with the root and start the direction at left to right. Each pass locks in the queue's size, records that many values left to right into one list, and enqueues their children left then right.","After a depth is collected, reverse its list only when the direction points right to left, then flip the direction for the next depth.","Watch the three depths fill on [3, 9, 20, null, null, 15, 7], and predict which lists get reversed."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","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":"Sweep three depths, flipping alternates","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"b-root","state":{"tree":[3,9,20,null,null,15,7],"node":0,"left_to_right":true,"arrays":[{"name":"queue","values":[3]},{"name":"level","values":[]}]}},{"id":"b-depth2","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2],"left_to_right":false,"arrays":[{"name":"queue","values":[9,20]},{"name":"level","values":[9,20]}]}},{"id":"b-depth3","state":{"tree":[3,9,20,null,null,15,7],"visited":[0,1,2],"swapped":[5,6],"left_to_right":true,"arrays":[{"name":"queue","values":[15,7]},{"name":"level","values":[15,7]}]}}]},"beats":[{"id":"b-root","title":"The first depth holds only the root. What does this pass record?","summary":"The root pass has width one.","options":[{"id":"record-3","label":"Record [3], enqueue 9 and 20, and flip the direction to right to left","rationale":"One node means the list [3] is complete, its children join the queue, and the flip sets up the next depth.","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":"reverse-now","label":"Reverse [3] before recording it","rationale":"The first direction is left to right, so the first depth is never reversed. A one-element list is the same either way, but the flag matters from the next depth on.","isCorrect":false}],"answer":"Record [3], enqueue 9 and 20, flip to right to left. Result so far: [[3]]."},{"id":"b-depth2","title":"This depth runs right to left. What gets recorded?","summary":"The second depth has been collected.","options":[{"id":"reverse-to-209","label":"Reverse the collected values to [20, 9]","rationale":"The right-to-left flag reverses the finished list to [20, 9]. Children still enqueue left then right, so the next depth is untouched.","isCorrect":true},{"id":"keep-920","label":"Record [9, 20] with no reverse","rationale":"The direction is right to left for this depth, so the values it collected have to come out reversed as [20, 9].","isCorrect":false},{"id":"flip-children","label":"Enqueue 15 and 7 in flipped order instead","rationale":"Reordering the children moves the flip into the next depth instead of this one. The reverse belongs to the values this depth just collected.","isCorrect":false}],"answer":"Reverse to [20, 9]. Result: [[3], [20, 9]]. The queue holds 15 then 7."},{"id":"b-depth3","title":"This depth runs left to right. What is recorded?","summary":"The final depth is ready to append.","options":[{"id":"keep-157","label":"[15, 7], with no reverse","rationale":"Left to right means the values stay in the order they were read. The queue empties after, so the sweep ends.","isCorrect":true},{"id":"reverse-715","label":"[7, 15], reversed like the depth before","rationale":"The flag alternates, so after the right-to-left depth this one is left to right again and is not reversed.","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], no reverse. The full result is [[3], [20, 9], [15, 7]]."}]},{"id":"enqueue-order-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could you flip the direction flag before deciding to reverse?","workspacePanel":"trace","summary":"Once a depth is collected it feels natural to flip the direction flag right away, then check the flag to decide whether to reverse the list just built. The flag still ends up alternating, and the first depth still comes out as [3]. Watch the next two depths on the sample.","pitfall":"The code below toggles left_to_right before the reverse check instead of after.","whyItMatters":"Flip the direction only after deciding whether to reverse the depth just collected. Toggling first reads the wrong flag: depth 1 stays [9, 20] when it should reverse, and depth 2 reverses to [7, 15] when it should stay put.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\nqueue = deque([root])\nleft_to_right = True\nwhile queue:\n    level_size = len(queue)\n    level = []\n    for _ in range(level_size):\n        node = queue.popleft()\n        level.append(node.val)\n        if node.left:\n            queue.append(node.left)\n        if node.right:\n            queue.append(node.right)\n    left_to_right = not left_to_right\n    if not left_to_right:\n        level.reverse()\n    result.append(level)\nreturn result","steps":[{"id":"pit-root","title":"Depth 0 collects [3], then the flag flips before the reverse check","codeLine":14,"summary":"Depth 0 collects [3]. The flag flips to right-to-left here, before the reverse check reads it.","state":{"tree":[3,9,20,null,null,15,7],"node":0,"swapped":[1,2]}},{"id":"pit-depth2-collect","title":"Depth 1 collects [9, 20], then flips the flag to left-to-right","codeLine":14,"summary":"Depth 1 collects [9, 20] in queue order. The flag was right-to-left for this depth, but the toggle flips it to left-to-right before the reverse check runs.","state":{"tree":[3,9,20,null,null,15,7],"node":2,"visited":[0]}},{"id":"pit-depth2-noreverse","title":"The reverse check reads the flipped flag and skips the reverse","codeLine":15,"summary":"The check reads left-to-right, the next depth's flag, so it leaves depth 1 as [9, 20]. The depth that should have reversed never does.","state":{"tree":[3,9,20,null,null,15,7],"node":2,"visited":[0]}},{"id":"pit-wrong","title":"Depth 2 reverses to [7, 15], and the result comes out wrong","codeLine":16,"summary":"Depth 2 collects [15, 7], flips the flag to right-to-left, and the check now reverses it to [7, 15]. The sweep returns [[3], [9, 20], [7, 15]]: depth 1 never reversed and depth 2 reversed when it should not have.","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 = new Deque([root]);\nlet leftToRight = true;\nwhile (queue.size() > 0) {\n    const levelSize = queue.size();\n    const level = [];\n    for (let i = 0; i < levelSize; i++) {\n        const node = queue.popFront();\n        level.push(node.val);\n        if (node.left) {\n            queue.pushBack(node.left);\n        }\n        if (node.right) {\n            queue.pushBack(node.right);\n        }\n    }\n    leftToRight = !leftToRight;\n    if (!leftToRight) {\n        level.reverse();\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":9,"10":10,"11":11,"12":13,"13":14,"14":17,"15":18,"16":19,"17":21,"18":23},"statementBundles":{"11":{"startLine":11,"endLine":12},"13":{"startLine":14,"endLine":16},"16":{"startLine":19,"endLine":20},"17":{"startLine":21,"endLine":22}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<Array<number>> = [];\nconst queue: Deque<TreeNode> = new Deque([root]);\nlet leftToRight = true;\nwhile (queue.size() > 0) {\n    const levelSize = queue.size();\n    const level: Array<number> = [];\n    for (let i = 0; i < levelSize; i++) {\n        const node = queue.popFront()!;\n        level.push(node.val);\n        if (node.left) {\n            queue.pushBack(node.left);\n        }\n        if (node.right) {\n            queue.pushBack(node.right);\n        }\n    }\n    leftToRight = !leftToRight;\n    if (!leftToRight) {\n        level.reverse();\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":9,"10":10,"11":11,"12":13,"13":14,"14":17,"15":18,"16":19,"17":21,"18":23},"statementBundles":{"11":{"startLine":11,"endLine":12},"13":{"startLine":14,"endLine":16},"16":{"startLine":19,"endLine":20},"17":{"startLine":21,"endLine":22}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> result = new ArrayList<>();\nDeque<TreeNode> queue = new ArrayDeque<>(List.of(root));\nboolean leftToRight = true;\nwhile (!queue.isEmpty()) {\n    int levelSize = queue.size();\n    List<Integer> level = new ArrayList<>();\n    for (int i = 0; i < levelSize; i++) {\n        TreeNode node = queue.pollFirst();\n        level.add(node.val);\n        if (node.left != null) {\n            queue.addLast(node.left);\n        }\n        if (node.right != null) {\n            queue.addLast(node.right);\n        }\n    }\n    leftToRight = !leftToRight;\n    if (!leftToRight) {\n        Collections.reverse(level);\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":9,"10":10,"11":11,"12":13,"13":14,"14":17,"15":18,"16":19,"17":21,"18":23},"statementBundles":{"11":{"startLine":11,"endLine":12},"13":{"startLine":14,"endLine":16},"16":{"startLine":19,"endLine":20},"17":{"startLine":21,"endLine":22}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> result = new();\nQueue<TreeNode> queue = new(new[] { root });\nbool leftToRight = true;\nwhile (queue.Count > 0) {\n    int levelSize = queue.Count;\n    List<int> level = new();\n    for (int i = 0; i < levelSize; i++) {\n        TreeNode node = queue.Dequeue();\n        level.Add(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    }\n    leftToRight = !leftToRight;\n    if (!leftToRight) {\n        level.Reverse();\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":9,"10":10,"11":11,"12":13,"13":14,"14":17,"15":18,"16":19,"17":21,"18":23},"statementBundles":{"11":{"startLine":11,"endLine":12},"13":{"startLine":14,"endLine":16},"16":{"startLine":19,"endLine":20},"17":{"startLine":21,"endLine":22}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> result;\ndeque<TreeNode*> queue{root};\nbool left_to_right = true;\nwhile (!queue.empty()) {\n    int level_size = queue.size();\n    vector<int> level;\n    for (int i = 0; i < level_size; i++) {\n        TreeNode* node = queue.front();\n        queue.pop_front();\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    left_to_right = !left_to_right;\n    if (!left_to_right) {\n        reverse(level.begin(), level.end());\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":12,"12":14,"13":15,"14":18,"15":19,"16":20,"17":22,"18":24},"statementBundles":{"8":{"startLine":8,"endLine":9},"11":{"startLine":12,"endLine":13},"13":{"startLine":15,"endLine":17},"16":{"startLine":20,"endLine":21},"17":{"startLine":22,"endLine":23}}}}}},{"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":["Recording the queue's size held each depth together, and the reverse only touched the values of alternate depths.","Now push on the shapes at the boundary: a tree with no root at all, and a tree that is only a root. Both settle before any child is ever enqueued."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-single","title":"Only the root: one depth, flag still left to right","summary":"A lone node 1 is one depth read left to right, before any child work exists.","state":{"tree":[1],"node":0}},{"id":"edge-intro-empty","title":"No root: nothing to seed the queue","summary":"With a null root there is no depth to collect, so the queue never gets seeded.","state":{"root":"null","arrays":[{"name":"queue","values":[]}]}}]}},{"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","arrays":[{"name":"queue","values":[]},{"name":"result","values":[]}]}}]},"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?","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, and the first pass has width 1.","options":[{"id":"single-level","label":"[[1]], read left to right with no reverse","rationale":"The first direction is left to right, so the one depth is recorded as [1] and never flipped, wrapped as [[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":"reversed","label":"[[1]] only after reversing the first level","rationale":"The first level is left to right, so it is never reversed. A one-element list is identical either way, but starting the flag wrong would flip the wrong levels later.","isCorrect":false}],"answer":"[[1]]. One depth, recorded left to right, with the first direction never reversed."},{"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":"Every decision the sweep makes, you have already made by hand.","body":["You know why the queue is there: it carries each depth forward so none of them has to be found again from the root.","You know the size you record before a pass is what keeps one depth from bleeding into the next, and that the direction only ever touches the values a depth collected, never the order its children go in."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"tree":[3,9,20,null,null,15,7],"node":0,"swapped":[1,2],"arrays":[{"name":"queue","values":[3]}]}}]}},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the zigzag sweep","summary":"Write the sweep so each depth comes out whole and only the alternate ones come out backward.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Carry it forward","title":"What to carry forward","summary":"You swept the tree depth by depth, reversing the values of every other one.","workspacePanel":"code","body":["Zigzag level order is ordinary breadth-first search with one small change at the end of each depth. Recording the queue's size before a pass is what groups nodes into depths, and the direction only reverses the values a depth already collected while the queue keeps fanning out left then right."],"takeaways":[{"title":"The size you record makes the depths","body":"Lock in the queue length before a pass and read exactly that many nodes, so the children enqueued meanwhile wait for the next depth."},{"title":"The reverse touches only the values","body":"The direction flips each alternate depth's values after they are collected: [9, 20] becomes [20, 9] while children still enqueue left then right."},{"title":"O(n) time and space","body":"Each node is read once and the queue holds at most one depth's width, so the sweep plus per-level reversals is linear."}],"nextAction":"Submit your solution to run it against every test case."}],"slidesOrigin":"authored","progressRevision":"zigzag-2026-08-08-cut-restatements-and-coinages"}}
