{"id":"minimum-depth-of-binary-tree","title":"Minimum Depth of 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","syntheticTestConfig":{"inputShape":"tree","primaryParam":"root","sizeMetric":"nodes","sizes":[1,3,7,15],"valueRange":{"min":-1000,"max":1000}},"description":"Given the root of a binary tree, return the minimum depth of the tree.\n\nThe minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. A leaf is a node with no children.","examples":[{"input":"root = [3,9,20,null,null,15,7]","output":"2","explanation":"Node 9 is the nearest leaf, so the shortest root-to-leaf path has 2 nodes."},{"input":"root = [2,null,3,null,4,null,5,null,6]","output":"5","explanation":"The only leaf is node 6, so the minimum depth follows the single chain."}],"constraints":[{"id":"the-number-of-nodes-in-the-tree-is-in-the-range-0-10-5","text":"The number of nodes in the tree is in the range [0, 10^5]","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":0,"max":100000}},{"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 minDepth(self, root: TreeNode) -> int:\n        # Your code here\n        pass","functionName":"minDepth","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":2,"description":"Balanced sample where the left child is the nearest leaf."},{"id":"2","input":{"root":{"val":1,"left":null,"right":null,"__id__":"tree-0"}},"expected":1,"description":"Single node tree."},{"id":"3","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":3,"description":"A skewed tree has only one root-to-leaf path."},{"id":"4","input":{"root":{"val":1,"left":{"val":2,"left":null,"right":null,"__id__":"tree-1"},"right":{"val":3,"left":{"val":4,"left":{"val":5,"left":null,"right":null,"__id__":"tree-4"},"right":null,"__id__":"tree-3"},"right":null,"__id__":"tree-2"},"__id__":"tree-0"}},"expected":2,"description":"The shallow left leaf should stop BFS before the deeper right chain."},{"id":"hidden-1","input":{"root":null},"expected":0,"description":"Empty tree."},{"id":"hidden-2","input":{"root":{"val":2,"left":null,"right":{"val":3,"left":null,"right":{"val":4,"left":null,"right":{"val":5,"left":null,"right":{"val":6,"left":null,"right":null,"__id__":"tree-4"},"__id__":"tree-3"},"__id__":"tree-2"},"__id__":"tree-1"},"__id__":"tree-0"}},"expected":5,"description":"Right-skewed chain."},{"id":"hidden-3","input":{"root":{"val":10,"left":null,"right":{"val":11,"left":null,"right":null,"__id__":"tree-1"},"__id__":"tree-0"}},"expected":2,"description":"A root with only one child reaches a leaf at depth two."},{"id":"hidden-4","input":{"root":{"val":1,"left":{"val":2,"left":{"val":4,"left":null,"right":null,"__id__":"tree-2"},"right":null,"__id__":"tree-1"},"right":{"val":3,"left":null,"right":null,"__id__":"tree-3"},"__id__":"tree-0"}},"expected":2,"description":"A shallow right leaf should beat a deeper left branch."},{"id":"hidden-5","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":3,"description":"A full three-level tree has minimum depth three."},{"id":"hidden-6","input":{"root":{"val":1,"left":{"val":2,"left":null,"right":{"val":4,"left":null,"right":null,"__id__":"tree-2"},"__id__":"tree-1"},"right":{"val":3,"left":{"val":5,"left":null,"right":null,"__id__":"tree-4"},"right":null,"__id__":"tree-3"},"__id__":"tree-0"}},"expected":3,"description":"Missing child pointers are not leaves; real leaves are on the third level."},{"id":"signed-values-short-leaf","input":{"root":{"__type__":"TreeNode","val":0,"left":{"__type__":"TreeNode","val":-2,"left":{"__type__":"TreeNode","val":-3,"left":null,"right":null},"right":null},"right":{"__type__":"TreeNode","val":4,"left":null,"right":null}}},"expected":2,"description":"Minimum depth uses the nearest leaf even when node values include zero and negatives."}],"hints":[{"level":1,"content":"A leaf at depth 2 should beat every deeper leaf, so process the tree by levels."},{"level":2,"content":"Use a queue and increase the depth once for each level."},{"level":3,"content":"The first leaf removed from the BFS frontier gives the minimum depth."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach finds the nearest leaf with the least work?","decisionPrompt":"On a tree with a shallow leaf on one side and a deep chain on the other, weigh how much each traversal explores before it can answer.","approaches":[{"id":"bfs-levels","name":"Level-order BFS, stop at the first leaf","summary":"Sweep the tree level by level with a queue, counting depth per level, and return the moment a leaf comes off the queue.","decisionReason":"Visiting by increasing depth means the first leaf is the shallowest, so the sweep can return at depth 2 here without ever descending the deeper branch.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":true},{"id":"dfs-all-paths","name":"DFS every root-to-leaf path","summary":"Recurse into both children of every node and keep the smallest leaf depth found.","decisionReason":"DFS returns the same minimum leaf depth in O(n) time. This flow uses BFS because the first leaf reached by a level frontier settles the answer without descending below it.","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["Runs in O(n) time and uses O(h) space."],"isViable":true,"isOptimal":false}]},"codingCheckpoints":[{"id":"init-frontier","title":"Start the BFS frontier","description":"Create the queue from the root and set up the traversal state.","commonMistakes":["Starting with an empty queue when the root exists","Forgetting to track depth"],"hint":"After the null-root guard, the queue should contain the root.","semanticSpec":{"intent":"Initialize the BFS queue and traversal state.","doneWhen":"The root is placed in a frontier before the BFS loop.","shouldFailWhen":"The traversal has no queue-like frontier.","roles":["root node","frontier queue"],"mustProve":["BFS state is initialized before traversal."],"mustNotAccept":["A recursive-only traversal with no BFS frontier."],"equivalentVariants":["Use a list with a head index, a deque, or a queue."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_bfs_result_and_queue","scope":"init-structures","readMode":"tree-value-query-v1"}]}},{"id":"init-depth","title":"Initialize depth","description":"Start a numeric depth counter before processing any level.","commonMistakes":["Returning edge count instead of node count","Incrementing depth for every node instead of every level"],"hint":"Depth should start before the BFS loop and advance by level.","semanticSpec":{"intent":"Initialize the numeric traversal depth.","doneWhen":"A numeric state is initialized before the BFS loop.","shouldFailWhen":"Depth is never tracked as state.","roles":["depth counter"],"mustProve":["A numeric traversal state is initialized."],"mustNotAccept":["Returning a constant depth."],"equivalentVariants":["Start depth at 0 and increment at the start of each level, or store depth with queued nodes."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]}},{"id":"bfs-loop","title":"Process queued nodes","description":"Continue while the BFS frontier still contains nodes.","commonMistakes":["Using only a single pass over the root","Never advancing through the queue"],"hint":"The loop should be driven by whether the frontier still has nodes.","semanticSpec":{"intent":"Drive the BFS traversal with the frontier.","doneWhen":"The code loops while the queue is non-empty.","shouldFailWhen":"Queued nodes are never consumed.","roles":["frontier queue","current node"],"mustProve":["A BFS frontier loop exists."],"mustNotAccept":["A fixed-depth traversal."],"equivalentVariants":["Use a head index, pop from the front, or dequeue."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"loops_while_bfs_frontier_non_empty","scope":"while-loop","readMode":"tree-value-query-v1"}]}},{"id":"process-level","title":"Test for a leaf, then queue its children","description":"For each node taken off the level, return at the current depth only when both the left and right child are absent; otherwise add whichever children exist to the back of the queue for the next level.","commonMistakes":["Stopping when either child is null instead of only when both are absent","Adding a null child to the queue instead of skipping it"],"hint":"A leaf has no child on either side, so the stop test is both children absent; a node with one child is not a leaf, so queue the child it does have.","semanticSpec":{"intent":"Process the nodes on the current level: a node with no left and no right child settles the answer, and every other node hands its existing children to the next level.","doneWhen":"The code stops at a node whose left and right are both absent, and enqueues each non-null child of the rest.","shouldFailWhen":"A node with one missing child is treated as a leaf, or a null child is enqueued.","roles":["current node","left child","right child","frontier queue"],"mustProve":["The leaf test fires only when both children are absent, and existing children are queued for the next level."],"mustNotAccept":["Returning when only one child is missing.","Enqueueing a null child."],"equivalentVariants":["Check each child with a null guard before appending, or filter the children before enqueueing."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"processes_frontier_level_nodes","scope":"process-level","readMode":"tree-value-query-v1"}]}},{"id":"return-depth","title":"Return the depth of the first leaf","description":"Return the current depth the moment a node with no children on either side comes off the queue.","commonMistakes":["Returning the number of queued nodes","Returning after seeing a single missing child instead of a real leaf"],"hint":"The answer is the depth carried when the first node with both children absent is reached.","semanticSpec":{"intent":"Return the tracked depth at the first leaf the sweep meets.","doneWhen":"The code returns the tracked numeric depth when a leaf is reached.","shouldFailWhen":"The result is unrelated to traversal depth.","roles":["depth counter","return value"],"mustProve":["A numeric state is returned."],"mustNotAccept":["Returning a queue or node object."],"equivalentVariants":["Return the level counter, or return a depth stored with the queued node."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]}}],"slides":[{"id":"read-the-signal","chapter":"The tree","kind":"info","eyebrow":"Read the problem","title":"How short is the shortest root-to-leaf path?","workspacePanel":"problem","body":["You get a binary tree. Its minimum depth is the number of nodes on the shortest path from the root down to a leaf, where a leaf is a node with no children at all.","Depth counts nodes on the path. A single node on its own has minimum depth 1."]},{"id":"brute-force","chapter":"The obvious way","kind":"code-trace","eyebrow":"Start naive","title":"Walk every path and keep the shortest","workspacePanel":"visualizer","body":["The direct approach recurses into both children of every node and reports the smaller leaf depth back up. The shortest of all root-to-leaf paths is the answer.","On a tree whose shortest leaf sits high on one side and whose other side runs deep, the recursion still walks the deep side before it can finish."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def min_depth(node: TreeNode | None) -> int:\n    if node is None:\n        return 0\n    if node.left is None and node.right is None:\n        return 1\n    best = float(\"inf\")\n    if node.left is not None:\n        best = min(best, min_depth(node.left))\n    if node.right is not None:\n        best = min(best, min_depth(node.right))\n    return best + 1","steps":[{"id":"bf-root","title":"Start at the root","codeLine":4,"summary":"Root 1 has two children, so it must compare both sides before it knows its own answer.","state":{"tree":[1,2,3,4,null,null,null,8],"node":0}},{"id":"bf-left-dive","title":"Dive down the long left side","codeLine":8,"summary":"The left child 2 leads to 4, then 8. The recursion walks all the way to depth 4 before this branch reports back.","state":{"tree":[1,2,3,4,null,null,null,8],"node":1,"visited":[1,3,7]}},{"id":"bf-right-leaf","title":"The right side is already a leaf","codeLine":10,"summary":"The right child 3 has no children, so its path is just 2 nodes. The real answer was reachable at depth 2.","state":{"tree":[1,2,3,4,null,null,null,8],"node":2,"visited":[1,3,7],"swapped":[2]}},{"id":"bf-combine","title":"Take the smaller path","codeLine":11,"summary":"The root reports 1 + min(deep left, shallow right) = 2. Correct, but it explored the depth-4 chain to learn an answer that lived at depth 2.","state":{"tree":[1,2,3,4,null,null,null,8],"node":0,"visited":[0,1,2,3,7]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (node === null) {\n    return 0;\n}\nif (node.left === null && node.right === null) {\n    return 1;\n}\nlet best = Infinity;\nif (node.left !== null) {\n    best = Math.min(best, minDepth(node.left));\n}\nif (node.right !== null) {\n    best = Math.min(best, minDepth(node.right));\n}\nreturn (best + 1);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":9,"9":11,"10":12,"11":14},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (node === null) {\n    return 0;\n}\nif (node.left === null && node.right === null) {\n    return 1;\n}\nlet best = Infinity;\nif (node.left !== null) {\n    best = Math.min(best, minDepth(node.left));\n}\nif (node.right !== null) {\n    best = Math.min(best, minDepth(node.right));\n}\nreturn (best + 1);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":9,"9":11,"10":12,"11":14},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (node == null) {\n    return 0;\n}\nif (node.left == null && node.right == null) {\n    return 1;\n}\ndouble best = double.PositiveInfinity;\nif (node.left != null) {\n    best = Math.Min(best, MinDepth(node.left));\n}\nif (node.right != null) {\n    best = Math.Min(best, MinDepth(node.right));\n}\nreturn checked((int)(best + 1));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":9,"9":11,"10":12,"11":14},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (node == nullptr) {\n    return static_cast<double>(0);\n}\nif ((node->left == nullptr && node->right == nullptr)) {\n    return static_cast<double>(1);\n}\ndouble best = numeric_limits<double>::infinity();\nif (node->left != nullptr) {\n    best = min(best, static_cast<double>(min_depth(node->left)));\n}\nif (node->right != nullptr) {\n    best = min(best, static_cast<double>(min_depth(node->right)));\n}\nreturn (best + 1);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":9,"9":11,"10":12,"11":14},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (node == null) {\n    return 0;\n}\nif (node.left == null && node.right == null) {\n    return 1;\n}\nint best = Integer.MAX_VALUE;\nif (node.left != null) {\n    best = Math.min(best, minDepth(node.left));\n}\nif (node.right != null) {\n    best = Math.min(best, minDepth(node.right));\n}\nreturn (best + 1);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":9,"9":11,"10":12,"11":14},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":13}}}}},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bf-root","title":"Start at the root","summary":"Root 1 has two children, so it must compare both sides before it knows its own answer.","state":{"tree":[1,2,3,4,null,null,null,8],"node":0}},{"id":"bf-left-dive","title":"Dive down the long left side","summary":"The left child 2 leads to 4, then 8. The recursion walks all the way to depth 4 before this branch reports back.","state":{"tree":[1,2,3,4,null,null,null,8],"node":1,"visited":[1,3,7]}},{"id":"bf-right-leaf","title":"The right side is already a leaf","summary":"The right child 3 has no children, so its path is just 2 nodes. The real answer was reachable at depth 2.","state":{"tree":[1,2,3,4,null,null,null,8],"node":2,"visited":[1,3,7],"swapped":[2]}},{"id":"bf-combine","title":"Take the smaller path","summary":"The root reports 1 + min(deep left, shallow right) = 2. Correct, but it explored the depth-4 chain to learn an answer that lived at depth 2.","state":{"tree":[1,2,3,4,null,null,null,8],"node":0,"visited":[0,1,2,3,7]}}]}},{"id":"waste-probe","chapter":"The obvious way","kind":"case-probe","eyebrow":"Find the waste","title":"What did the full walk explore that it never needed?","workspacePanel":"trace","options":[{"id":"deep-chain","label":"The whole left chain below depth 2, since a shallower leaf already existed","rationale":"Once a leaf appears at depth 2, nothing deeper can beat it. The full walk still descends the depth-4 left chain before it can compare, doing work that the answer never depended on.","isCorrect":true},{"id":"right-leaf","label":"The right leaf 3, which it visited for nothing","rationale":"The right leaf is exactly the answer. It was the deep left side, explored past depth 2, that was the wasted work.","isCorrect":false},{"id":"root-itself","label":"The root, which it did not need to visit","rationale":"Every path starts at the root, so it must be visited. The avoidable work is descending below the shallowest leaf.","isCorrect":false}],"answer":"The deep left chain below depth 2. Once a leaf is found at depth 2, nothing deeper can be the minimum, yet the full walk still explores it.","summary":"The shortest leaf, node 3, sits at depth 2 on the right. The left chain 2, 4, 8 runs down to depth 4."},{"id":"discover-order","chapter":"The trick","kind":"case-probe","eyebrow":"Find the order","title":"Which visiting order reaches the nearest leaf first?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"order-state","state":{"tree":[1,2,3,4,null,null,null,8],"node":0,"swapped":[1,2]}}]},"options":[{"id":"by-level","label":"Visit every node at depth 1, then every node at depth 2, and so on","rationale":"Visiting strictly by increasing depth means the very first leaf you meet is at the smallest possible depth. You can stop right there, never touching a deeper node.","isCorrect":true},{"id":"one-branch","label":"Follow one branch to its leaf, then back up and try the next","rationale":"That is the depth-first walk we just saw. It can plunge down a long branch and reach a deep leaf before ever seeing the shallow one on the other side.","isCorrect":false},{"id":"values","label":"Visit nodes in increasing order of their stored values","rationale":"Node values have nothing to do with depth. A small value can sit deep and a large value can sit shallow.","isCorrect":false}],"answer":"Visit nodes by increasing depth, level by level. The first leaf you meet is then guaranteed to be the shallowest, so you can stop immediately.","summary":"We want to stop the moment we meet a leaf, without exploring anything deeper than it."},{"id":"first-leaf","chapter":"The trick","kind":"case-probe","eyebrow":"Name the stop","title":"When the level sweep meets its first leaf, what is the answer?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-leaf-state","state":{"tree":[3,9,20,null,null,15,7],"node":1,"visited":[0],"swapped":[1]}}]},"options":[{"id":"current-depth","label":"The depth of the level you are on, here 2","rationale":"Because the sweep has already finished every shallower level, the depth of the first leaf is the minimum depth. Node 9 sits on level 2, so the answer is 2 and the sweep can stop.","isCorrect":true},{"id":"keep-going","label":"Unknown yet, keep sweeping in case a shallower leaf appears later","rationale":"No shallower leaf can appear later. The sweep already cleared every level above this one, so the first leaf it meets is the shallowest that exists.","isCorrect":false},{"id":"count-leaves","label":"The number of leaves seen so far","rationale":"Minimum depth is about how deep the nearest leaf is, not how many leaves exist. One leaf at the current level is enough to answer.","isCorrect":false}],"answer":"The depth of the current level. Every shallower level is already done, so the first leaf the sweep meets is the shallowest, and its level is the minimum depth.","summary":"Sweeping the example by level, the root 3 is processed, then its level-2 nodes 9 and 20 come up. Node 9 has no children."},{"id":"approach-selection","chapter":"The trick","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which approach finds the nearest leaf with the least work?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"tree":[1,2,3,4,null,null,null,8],"node":0,"swapped":[1,2]}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Sweep the example level by level","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"tree":[3,9,20,null,null,15,7],"node":0,"depth":0,"arrays":[{"name":"queue","values":[3]}]}}]},"body":["Put the root 3 into a queue and let the depth count climb by one for each level the sweep finishes.","At each level, take the nodes that are waiting, check each for being a leaf, and add the children of the rest to the back of the queue for the next level.","The first leaf that comes off the queue ends the run, and the level it sits on is the answer."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the sweep","title":"Stop at the first leaf","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"beat-seed","state":{"tree":[3,9,20,null,null,15,7],"node":0,"swapped":[0],"depth":1,"arrays":[{"name":"queue","values":[3]}]}},{"id":"beat-expand","state":{"tree":[3,9,20,null,null,15,7],"visited":[0],"swapped":[1,2],"depth":2,"arrays":[{"name":"queue","values":[9,20]}]}},{"id":"beat-leaf","state":{"tree":[3,9,20,null,null,15,7],"node":1,"visited":[0],"swapped":[1],"depth":2,"arrays":[{"name":"queue","values":[20]}]}}]},"beats":[{"id":"beat-seed","title":"The root is not a leaf. What does the sweep do with it?","summary":"Depth has reached 1 and the queue holds only the root 3, which has two children.","options":[{"id":"enqueue","label":"Record its two children for the next level and move on","rationale":"The root has children 9 and 20, so it is not a leaf. The sweep adds them to the queue and advances the depth count to the next level.","isCorrect":true},{"id":"return-one","label":"Return depth 1, since the root is where we started","rationale":"Depth 1 would be the answer only if the root itself had no children. It has two, so the nearest leaf is deeper.","isCorrect":false},{"id":"skip","label":"Skip it and start at its children","rationale":"The root must be checked first in case it is itself a leaf. Here it is not, so its children are queued for the next level.","isCorrect":false}],"answer":"It is not a leaf, so its children 9 and 20 are queued for the next level and the depth count moves to 2."},{"id":"beat-expand","title":"Level 2 now holds 9 and 20. Which one is examined first?","summary":"The queue holds 9 then 20, in the order they were added.","options":[{"id":"fifo","label":"Node 9, because the queue hands back the earliest-added node first","rationale":"A queue is first-in first-out, so 9, added before 20, comes off first. That left-to-right order within the level is exactly what keeps the sweep honest about depth.","isCorrect":true},{"id":"lifo","label":"Node 20, the most recently added","rationale":"Taking the newest node first is stack behavior. That turns the sweep depth-first and breaks the by-level order.","isCorrect":false},{"id":"smaller","label":"Node 9, because its value is smaller than 20","rationale":"9 does come first, but not because of its value. The queue returns it first because it was added first.","isCorrect":false}],"answer":"Node 9, because the queue returns the earliest-added node first. Both nodes sit on level 2 regardless."},{"id":"beat-leaf","title":"A leaf appears mid-level. Why can the sweep stop now instead of finishing the level?","summary":"Node 9 has just come off the queue at depth 2, but its sibling 20 is still waiting on this same level.","options":[{"id":"stop-now","label":"Nothing on this level or below can be shallower, so it returns at once","rationale":"Every level above 2 is already cleared, and 20 sits on the same level as 9, not above it. No node still to be seen can beat depth 2, so the sweep returns the instant the leaf appears.","isCorrect":true},{"id":"check-20","label":"It cannot stop yet; it must finish the level by checking 20 first","rationale":"Checking 20 cannot lower the answer. It is on the same level as 9, so even if it were also a leaf the depth would still be 2. Finishing the level is wasted work once a leaf is in hand.","isCorrect":false},{"id":"compare-children","label":"It must expand 20 and compare its children before deciding","rationale":"The children of 20 sit at depth 3, deeper than the leaf already found. Expanding them only explores nodes that cannot be the minimum.","isCorrect":false}],"answer":"It stops immediately. Node 9 is a leaf on level 2, every shallower level is done, and the rest of this level and everything below it can only be as deep or deeper, so finishing the level would change nothing."}]},{"id":"one-sided-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Is a node with one missing child a leaf?","workspacePanel":"trace","summary":"This version calls a node a leaf the moment one child pointer is null. Watch it judge a lopsided chain.","pitfall":"The stop test below fires when either child is missing, instead of only when both children are missing.","whyItMatters":"A leaf is a node with no children on either side. A node with one child is not a leaf; the path must continue through the child it does have. Stop only when both the left and right child are absent.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def min_depth(root: TreeNode | None) -> int:\n    queue = [root]\n    depth = 0\n    while queue:\n        depth += 1\n        node = queue.pop(0)\n        if node.left is None or node.right is None:\n            return depth\n        queue.append(node.left)\n        queue.append(node.right)","steps":[{"id":"pf-root","title":"A chain 1 then 2 then 3","codeLine":2,"summary":"The tree is a left-only chain: 1 has a left child 2, which has a left child 3. The real minimum depth is 3, the only leaf.","state":{"tree":[1,2,null,3],"node":0}},{"id":"pf-check","title":"Root 1 has no right child","codeLine":7,"summary":"The root has a left child 2 but its right side is empty. The broken test sees one missing side and treats the root as a leaf.","state":{"tree":[1,2,null,3],"node":0,"swapped":[0]}},{"id":"pf-wrong","title":"It returns depth 1","codeLine":8,"summary":"The sweep stops at the root and reports 1, but the nearest real leaf, node 3, is at depth 3. The one-child node was never a leaf.","state":{"tree":[1,2,null,3],"node":0,"visited":[0]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const queue = [root];\nlet depth = 0;\nwhile (queue.length > 0) {\n    depth++;\n    const node = queue.shift();\n    if (node.left === null || node.right === null) {\n        return depth;\n    }\n    queue.push(node.left);\n    queue.push(node.right);\n}","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const queue = [root];\nlet depth = 0;\nwhile (queue.length > 0) {\n    depth++;\n    const node = queue.shift()!;\n    if (node.left === null || node.right === null) {\n        return depth;\n    }\n    queue.push(node.left);\n    queue.push(node.right);\n}","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"Queue<TreeNode> queue = new(new[] { root });\nint depth = 0;\nwhile (queue.Count > 0) {\n    depth++;\n    TreeNode node = queue.Dequeue();\n    if (node.left == null || node.right == null) {\n        return depth;\n    }\n    queue.Enqueue(node.left);\n    queue.Enqueue(node.right);\n}","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"deque<TreeNode*> queue{root};\nint depth = 0;\nwhile (!queue.empty()) {\n    depth++;\n    TreeNode* node = queue.front();\n    queue.pop_front();\n    if ((node->left == nullptr || node->right == nullptr)) {\n        return depth;\n    }\n    queue.push_back(node->left);\n    queue.push_back(node->right);\n}","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":10,"10":11},"statementBundles":{"6":{"startLine":5,"endLine":6},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<TreeNode> queue = new ArrayList<>(List.of(root));\nint depth = 0;\nwhile (!queue.isEmpty()) {\n    depth++;\n    TreeNode node = queue.remove(0);\n    if (node.left == null || node.right == null) {\n        return depth;\n    }\n    queue.add(node.left);\n    queue.add(node.right);\n}","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Stopping at the first leaf held for a normal tree, and we just saw that a one-child node is not a leaf. The shapes that strain a level sweep are the smallest ones, where the sweep barely runs at all.","Worth checking before coding: a tree with no nodes whatsoever, and a tree that is just a single lone node with nothing below it."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"tree":[5],"node":0}}]}},{"id":"edge-empty","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What should an empty tree return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-empty-state","state":{"tree":[]}}]},"options":[{"id":"zero","label":"0, with no level ever entered","rationale":"With no root there is no first level to sweep, so the depth count never reaches 1. An empty tree has minimum depth 0.","isCorrect":true},{"id":"one","label":"1, the first level","rationale":"Returning 1 assumes a node to stand on. There is none, so the sweep must report 0 before any level begins.","isCorrect":false},{"id":"crash","label":"It cannot answer and should error","rationale":"An empty tree is a valid input with a clear answer of 0. Guard it up front rather than letting the sweep touch a missing node.","isCorrect":false}],"answer":"0. With no root, the sweep never enters a level, so the depth stays at 0.","summary":"The root itself is missing, so there is no node and no path to any leaf."},{"id":"edge-single","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"A lone root with no children: what does the sweep return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-single-state","state":{"tree":[5],"node":0,"swapped":[0]}}]},"options":[{"id":"one","label":"1, because the root itself is the leaf","rationale":"The sweep enters the first level, takes the root, and finds it has no children on either side. The very first node is already a leaf, so the answer is its depth, 1.","isCorrect":true},{"id":"zero","label":"0, since there is nothing below the root","rationale":"0 is the answer for an empty tree, where no node exists at all. Here a node does exist and stands on level 1, so the minimum depth is 1, not 0.","isCorrect":false},{"id":"two","label":"2, counting the root and one step down","rationale":"There is no step down to count; the root has no children. The path is the single node 5, which is 1 node, so the depth is 1.","isCorrect":false}],"answer":"1. The root is checked on the first level, has no children on either side, and is therefore a leaf, so the sweep returns depth 1.","summary":"The whole tree is one node, the root 5. It has no left child and no right child."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"A missing child is not a leaf, so stop only when both sides are empty.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"tree":[3,9,20,null,null,15,7],"node":0,"depth":0,"arrays":[{"name":"queue","values":[3]}]}}]},"body":["Guard the empty tree, seed a queue with the root, and let a depth count climb by one for each level the sweep enters.","On each level, pull the waiting nodes; the first one with no children at all settles the answer at the current depth, and every other node hands its children to the back of the queue for the next level."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the shallowest-leaf search","eyebrow":"Code the rule","summary":"Sweep level by level, stop only when a node has no children on either side, and carry each existing child to the next level.","workspacePanel":"code","checkpoints":[{"id":"init-frontier","title":"Start the BFS frontier","description":"Create the queue from the root and set up the traversal state.","commonMistakes":["Starting with an empty queue when the root exists","Forgetting to track depth"],"hint":"After the null-root guard, the queue should contain the root.","semanticSpec":{"intent":"Initialize the BFS queue and traversal state.","doneWhen":"The root is placed in a frontier before the BFS loop.","shouldFailWhen":"The traversal has no queue-like frontier.","roles":["root node","frontier queue"],"mustProve":["BFS state is initialized before traversal."],"mustNotAccept":["A recursive-only traversal with no BFS frontier."],"equivalentVariants":["Use a list with a head index, a deque, or a queue."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_bfs_result_and_queue","scope":"init-structures","readMode":"tree-value-query-v1"}]}},{"id":"init-depth","title":"Initialize depth","description":"Start a numeric depth counter before processing any level.","commonMistakes":["Returning edge count instead of node count","Incrementing depth for every node instead of every level"],"hint":"Depth should start before the BFS loop and advance by level.","semanticSpec":{"intent":"Initialize the numeric traversal depth.","doneWhen":"A numeric state is initialized before the BFS loop.","shouldFailWhen":"Depth is never tracked as state.","roles":["depth counter"],"mustProve":["A numeric traversal state is initialized."],"mustNotAccept":["Returning a constant depth."],"equivalentVariants":["Start depth at 0 and increment at the start of each level, or store depth with queued nodes."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]}},{"id":"bfs-loop","title":"Process queued nodes","description":"Continue while the BFS frontier still contains nodes.","commonMistakes":["Using only a single pass over the root","Never advancing through the queue"],"hint":"The loop should be driven by whether the frontier still has nodes.","semanticSpec":{"intent":"Drive the BFS traversal with the frontier.","doneWhen":"The code loops while the queue is non-empty.","shouldFailWhen":"Queued nodes are never consumed.","roles":["frontier queue","current node"],"mustProve":["A BFS frontier loop exists."],"mustNotAccept":["A fixed-depth traversal."],"equivalentVariants":["Use a head index, pop from the front, or dequeue."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"loops_while_bfs_frontier_non_empty","scope":"while-loop","readMode":"tree-value-query-v1"}]}},{"id":"process-level","title":"Test for a leaf, then queue its children","description":"For each node taken off the level, return at the current depth only when both the left and right child are absent; otherwise add whichever children exist to the back of the queue for the next level.","commonMistakes":["Stopping when either child is null instead of only when both are absent","Adding a null child to the queue instead of skipping it"],"hint":"A leaf has no child on either side, so the stop test is both children absent; a node with one child is not a leaf, so queue the child it does have.","semanticSpec":{"intent":"Process the nodes on the current level: a node with no left and no right child settles the answer, and every other node hands its existing children to the next level.","doneWhen":"The code stops at a node whose left and right are both absent, and enqueues each non-null child of the rest.","shouldFailWhen":"A node with one missing child is treated as a leaf, or a null child is enqueued.","roles":["current node","left child","right child","frontier queue"],"mustProve":["The leaf test fires only when both children are absent, and existing children are queued for the next level."],"mustNotAccept":["Returning when only one child is missing.","Enqueueing a null child."],"equivalentVariants":["Check each child with a null guard before appending, or filter the children before enqueueing."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"processes_frontier_level_nodes","scope":"process-level","readMode":"tree-value-query-v1"}]}},{"id":"return-depth","title":"Return the depth of the first leaf","description":"Return the current depth the moment a node with no children on either side comes off the queue.","commonMistakes":["Returning the number of queued nodes","Returning after seeing a single missing child instead of a real leaf"],"hint":"The answer is the depth carried when the first node with both children absent is reached.","semanticSpec":{"intent":"Return the tracked depth at the first leaf the sweep meets.","doneWhen":"The code returns the tracked numeric depth when a leaf is reached.","shouldFailWhen":"The result is unrelated to traversal depth.","roles":["depth counter","return value"],"mustProve":["A numeric state is returned."],"mustNotAccept":["Returning a queue or node object."],"equivalentVariants":["Return the level counter, or return a depth stored with the queued node."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"A level sweep that stops at its first leaf reads the minimum depth straight off that level.","workspacePanel":"code","body":["Breadth-first order visits shallower nodes before deeper ones, so the nearest leaf is always the first leaf the sweep meets.","The same level sweep underlies shortest-path counting on unweighted graphs: equal-cost steps mean the first arrival is the closest one."],"takeaways":[{"title":"The first leaf BFS meets is the shallowest","body":"A queue clears each level fully before the next, so the first leaf off the queue sits at the smallest depth that any leaf reaches."},{"title":"A missing child is not a leaf","body":"Stop only when both the left and right child are absent. A node with one child still has a path running through it, so the sweep must continue."},{"title":"Stopping early is the whole win","body":"Returning the moment a leaf appears avoids exploring any deeper branch, which is exactly the work the full depth-first walk wasted."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
