{"id":"diameter-of-binary-tree","title":"Diameter of Binary Tree","difficulty":"easy","patterns":["tree-dfs"],"primaryConcept":"tree-dfs-global-optimum","concepts":["tree-dfs-global-optimum"],"problemForm":"intro","companies":[],"category":"trees-graphs","compareMode":"exact","description":"Given the root of a binary tree, return the length of the tree's diameter.\n\nThe diameter is the number of edges on the longest path between any two nodes. The path may pass through the root, but it does not have to.","examples":[{"input":"root = {\"val\":1,\"left\":{\"val\":2,\"left\":{\"val\":4},\"right\":{\"val\":5}},\"right\":{\"val\":3}}","output":"3","explanation":"The longest path is 4 -> 2 -> 1 -> 3 or 5 -> 2 -> 1 -> 3, which has 3 edges."},{"input":"root = {\"val\":1}","output":"0","explanation":"A single node has no edges, so its diameter is 0."},{"input":"root = null","output":"0","explanation":"An empty tree has no path."}],"constraints":[{"id":"the-number-of-nodes-in-the-tree-is-in-the-range-0-10-4","text":"The number of nodes in the tree is in the range [0, 10^4]","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":0,"max":10000}},{"id":"100-node-val-100","text":"-100 <= Node.val <= 100","check":{"kind":"valueRange","target":"root","selector":"treeValues","min":-100,"max":100}},{"id":"the-answer-is-measured-in-edges-not-nodes","text":"The answer is measured in edges, not nodes"}],"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 diameterOfBinaryTree(self, root: TreeNode | None) -> int:\n        # Your code here\n        pass","functionName":"diameterOfBinaryTree","testCases":[{"id":"1","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-3","val":4,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-4","val":5,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":null,"right":null}}},"expected":3,"description":"Classic example where the best path goes through the root."},{"id":"2","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":null,"right":null}},"expected":0,"description":"Single node has diameter 0."},{"id":"3","input":{"root":null},"expected":0,"description":"Empty tree has no edges."},{"id":"4","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":{"__type__":"TreeNode","__id__":"tree-3","val":4,"left":null,"right":null},"right":null},"right":null},"right":null}},"expected":3,"description":"Left-skewed tree where the longest path is the whole chain."},{"id":"5","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-3","val":4,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-4","val":5,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":{"__type__":"TreeNode","__id__":"tree-5","val":6,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-6","val":7,"left":null,"right":null}}}},"expected":4,"description":"Imported trusted-corpus shape with deepest leaves on opposite sides."},{"id":"h1","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":null,"right":null},"right":null}},"expected":1,"description":"A single edge from root to child."},{"id":"h2","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-3","val":4,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"tree-4","val":5,"left":null,"right":null}}},"expected":3,"description":"A deeper left subtree still routes through the root."},{"id":"h3","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-3","val":4,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"tree-4","val":5,"left":{"__type__":"TreeNode","__id__":"tree-5","val":6,"left":null,"right":null},"right":null}}},"expected":4,"description":"The longest path crosses two uneven subtrees."},{"id":"h4","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":{"__type__":"TreeNode","__id__":"tree-3","val":4,"left":null,"right":null},"right":null},"right":null},"right":{"__type__":"TreeNode","__id__":"tree-4","val":5,"left":{"__type__":"TreeNode","__id__":"tree-5","val":6,"left":null,"right":null},"right":null}}},"expected":5,"description":"A long left chain and a shorter right chain meet at the root."},{"id":"h5","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-3","val":4,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-4","val":5,"left":null,"right":null}}}}}},"expected":4,"description":"A right-skewed chain mirrors the left-skewed base case."},{"id":"signed-values-do-not-affect-diameter","input":{"root":{"__type__":"TreeNode","val":0,"left":{"__type__":"TreeNode","val":-2,"left":{"__type__":"TreeNode","val":-4,"left":null,"right":null},"right":{"__type__":"TreeNode","val":-1,"left":null,"right":null}},"right":{"__type__":"TreeNode","val":3,"left":null,"right":{"__type__":"TreeNode","val":5,"left":null,"right":null}}}},"expected":4,"description":"Diameter depends on tree shape, not zero or negative node values."}],"hints":[{"level":1,"content":"At each node, the best path passing through that node uses the left depth plus the right depth.","revealPattern":false},{"level":2,"content":"Use DFS to `return` subtree height while updating a separate best diameter.","revealPattern":true},{"level":3,"content":"Return `max(left, right) + 1` upward, but update the answer with `left + right`.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"all-pairs-paths","name":"Try every pair of nodes","summary":"Compare distances between many pairs of nodes.","decisionReason":"It returns the right answer but re-walks the same branches for every pair of nodes, an n^2 blowup that re-measures depths each node already knows.","complexity":{"time":"O(n^2)","space":"O(h)"},"tradeoffs":["Runs in O(n^2) time and uses O(h) space."],"isOptimal":false},{"id":"height-dfs","name":"Postorder height DFS","summary":"Return each subtree height and update the best diameter with left height plus right height.","decisionReason":"One depth-first walk returns each subtree depth and updates a separate best-bend maximum with left + right, measuring every node's longest path in a single linear pass.","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["Runs in O(n) time and uses O(h) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-diameter","title":"Initialize the best diameter","description":"Start a numeric tracker at 0 because a diameter counts edges.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_recursive_zero_extremum_tracker","scope":"init-diameter","readMode":"tree-value-query-v1"}]},"commonMistakes":["Starting at 1 and counting nodes instead of edges","Returning height directly without tracking the best left-plus-right path"],"hint":"The smallest possible diameter is 0 edges.","semanticSpec":{"intent":"Create a numeric tracker for the best diameter seen so far.","doneWhen":"This step is done when the solution initializes a numeric best-diameter state to 0.","shouldFailWhen":"This step should fail if there is no numeric tracker or if the tracker starts as a node count.","roles":["diameter tracker","zero edge count"],"mustProve":["A numeric state is initialized to 0."],"mustNotAccept":["Returning subtree height without a separate best value."],"equivalentVariants":["Use a local nonlocal variable, a mutable cell, or an instance field initialized to 0."],"proofSnippets":[{"id":"py-init-diameter","language":"python","code":"def diameterOfBinaryTree(root):\n    diameter = 0"}]}},{"id":"recursive-heights","title":"Compute both child heights","description":"Use a recursive helper that returns 0 for missing nodes and recurses into both children.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"guards_and_recurses_into_child_subtrees","scope":"recursive-step","readMode":"tree-value-query-v1"}]},"commonMistakes":["Exploring only one child","Forgetting the empty-node base case"],"hint":"The helper should return the height of the subtree rooted at the current node.","semanticSpec":{"intent":"Define the height recursion over both child subtrees.","doneWhen":"This step is done when a helper guards missing nodes and obtains recursive heights from both left and right children.","shouldFailWhen":"This step should fail if only one child contributes or if the missing-node case is not guarded.","roles":["current node","left height","right height"],"mustProve":["The helper returns 0 for a missing node.","The helper recurses on both child links."],"mustNotAccept":["Using the same child for both recursive calls."],"equivalentVariants":["Store child heights in variables or inline them in later expressions."]}},{"id":"update-diameter","title":"Update with left plus right","description":"At each node, compare the best diameter with the path that uses both child heights.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"updates_recursive_child_pair_extremum","scope":"update-diameter","readMode":"tree-value-query-v1"}]},"commonMistakes":["Updating with max(left, right) instead of left + right","Adding 1 when updating the diameter and accidentally counting nodes"],"hint":"The path through a node has `left + right` edges.","semanticSpec":{"intent":"Use the pair of child heights to update the global best diameter.","doneWhen":"This step is done when the tracker is updated with a max-like comparison against left height plus right height.","shouldFailWhen":"This step should fail if the update reads only one child height or counts the current node as an extra edge.","roles":["left height","right height","diameter tracker"],"mustProve":["The update reads both captured child heights.","The tracked best value is updated through a max-like operation."],"mustNotAccept":["Using only one child height.","Returning the candidate path without tracking the best across all nodes."],"equivalentVariants":["Assign `diameter = max(diameter, left + right)` or update an equivalent mutable tracker."]}},{"id":"return-height","title":"Return height to the parent","description":"Return the deeper child height plus one so the parent can compute its own diameter candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_combined_child_extremum","scope":"return-max-plus-one","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning left + right upward","Forgetting to add one for the current node's height"],"hint":"A parent can continue through only one child branch.","semanticSpec":{"intent":"Return the current subtree height rather than the local diameter.","doneWhen":"This step is done when the helper returns max(left, right) + 1.","shouldFailWhen":"This step should fail if the helper returns left + right or omits the current node.","roles":["left height","right height","returned height"],"mustProve":["The return chooses the larger child height.","The return adds one for the current node."],"mustNotAccept":["Returning both child heights upward as a path.","Returning the tracked diameter from inside the helper."],"equivalentVariants":["Return `1 + max(left, right)` or an equivalent expression."],"proofSnippets":[{"id":"py-return-height","language":"python","code":"def diameterOfBinaryTree(root):\n    diameter = 0\n\n    def depth(node):\n        nonlocal diameter\n        if not node:\n            return 0\n        left = depth(node.left)\n        right = depth(node.right)\n        diameter = max(diameter, left + right)\n        return max(left, right) + 1"}]}},{"id":"start-dfs","title":"Run DFS from the root","description":"Start the height helper at the original root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"invokes_recursive_child_helper_with_root","scope":"start-dfs","readMode":"tree-value-query-v1"}]},"commonMistakes":["Defining the helper but never calling it","Calling the helper on a child instead of the root"],"hint":"The helper must visit the whole tree, starting from root.","semanticSpec":{"intent":"Execute the height recursion over the original tree root.","doneWhen":"This step is done when the helper is invoked with the original root.","shouldFailWhen":"This step should fail if the helper is not started at root.","roles":["root","height helper"],"mustProve":["The helper is invoked with the original root."],"mustNotAccept":["Calling the helper on a non-root object."],"equivalentVariants":["Call the DFS on root before returning the tracker."],"proofSnippets":[{"id":"py-start-dfs","language":"python","code":"def diameterOfBinaryTree(root):\n    diameter = 0\n\n    def depth(node):\n        nonlocal diameter\n        if not node:\n            return 0\n        left = depth(node.left)\n        right = depth(node.right)\n        diameter = max(diameter, left + right)\n        return max(left, right) + 1\n\n    depth(root)"}]}},{"id":"return-diameter","title":"Return the best diameter","description":"Return the best diameter found across all nodes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_recursive_extremum_tracker","scope":"return-global-max","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning the root height instead of the tracked diameter","Returning the helper result directly"],"hint":"The helper computes heights for side effects on the best diameter tracker.","semanticSpec":{"intent":"Return the tracked answer after DFS finishes.","doneWhen":"This step is done when the outer function returns the best-diameter tracker.","shouldFailWhen":"This step should fail if the function returns subtree height instead of the tracker.","roles":["diameter tracker"],"mustProve":["The final return uses the tracked diameter state."],"mustNotAccept":["Returning the helper call result directly."],"equivalentVariants":["Return the numeric tracker after the helper has visited the tree."],"proofSnippets":[{"id":"py-return-diameter","language":"python","code":"def diameterOfBinaryTree(root):\n    diameter = 0\n\n    def depth(node):\n        nonlocal diameter\n        if not node:\n            return 0\n        left = depth(node.left)\n        right = depth(node.right)\n        diameter = max(diameter, left + right)\n        return max(left, right) + 1\n\n    depth(root)\n    return diameter"}]}}],"version":2,"slides":[{"id":"the-task","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"The longest path through a tree","workspacePanel":"problem","body":["The diameter of a binary tree is the number of edges on the longest path between any two nodes. That path can bend through a node, but it never has to touch the root.","The count is edges, not nodes. A single node has diameter 0, and an empty tree has diameter 0 as well."]},{"id":"pattern-quiz","chapter":"The problem","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"Where does each node get the answer it reports?","workspacePanel":"problem","quiz":{"contract":"pattern-recognition-v1","question":"Where does each node get the answer it reports?","signalPrompt":"The longest path can turn at any node, and a path that bends there needs how far both of that node's sides reach. Which traversal lets a node learn both of its sides before it is judged?","options":[{"id":"assembled-from-children","label":"Each node assembles its answer from results its two children report back","signal":"A node cannot judge the path turning at it until both child subtrees have reported up.","rationale":"The answer at a node depends on what its children return, and that bottom-up \"children first, then me\" shape is exactly a postorder DFS.","isCorrect":true},{"id":"all-pairs","label":"Each node compares itself against every other node in the tree","signal":"Comparing every node to every other node sounds thorough.","rationale":"All-pairs comparison answers the question but ignores that a child already holds the result its parent needs, so it points at no single clean traversal.","isCorrect":false},{"id":"level-order","label":"Each level is finished before the next one begins, top to bottom","signal":"Sweeping the tree level by level is what a breadth-first pass does.","rationale":"A top-down level sweep finishes parents before children, so a parent never sees what its children would report back upward.","isCorrect":false},{"id":"top-down-depth","label":"Each node is handed its depth from above, before its children are seen","signal":"Passing a running depth down from the root, parent before children, is a natural top-down preorder pass.","rationale":"Computing depth on the way down tells each node how far it sits below the root, but a bend turns at a node and needs how far BOTH children reach back up. A parent-before-children pass never gathers those two child results, so it cannot measure the path that bends at a node.","isCorrect":false}],"missFeedback":"A node can only judge the path through it once its children have reported back. That children-first order is a bottom-up DFS.","hint":"Ask which traversal lets a parent see results from both children before it decides."}},{"id":"brute-force","chapter":"The obvious way","kind":"code-trace","eyebrow":"Start naive","title":"Measure every node's bend from scratch","summary":"Re-measuring both sides from scratch at every node gets each bend right, but the shallow branches get re-walked on every pass. Watch how much of the tree the descents retrace.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def diameterOfBinaryTree(root: TreeNode | None) -> int:\n    def height(node: TreeNode | None) -> int:\n        if not node:\n            return 0\n        return 1 + max(height(node.left), height(node.right))\n\n    def best_bend(node: TreeNode | None) -> int:\n        if not node:\n            return 0\n        here = height(node.left) + height(node.right)\n        below = max(best_bend(node.left), best_bend(node.right))\n        return max(here, below)\n\n    return best_bend(root)","steps":[{"id":"measure-root","title":"The root measures both sides","codeLine":10,"summary":"Tree [1, 2, 3, 4, null, null, 5]. At node 1 the scan calls height on each side. Each call descends the whole subtree: height(node 2) walks down to leaf 4 and reports 2, height(node 3) walks down to leaf 5 and reports 2. The bend is 2 + 2 = 4.","state":{"tree":[1,2,3,4,null,null,5],"node":0,"swapped":[1,2]}},{"id":"measure-node-two","title":"Node 2 re-descends the same branch","codeLine":10,"summary":"The scan moves to node 2 and calls height again. height(node 4) walks down to leaf 4 once more, the very descent that just happened while measuring the root. Node 2's bend is height(4) + height(empty) = 1 + 0 = 1.","state":{"tree":[1,2,3,4,null,null,5],"node":1,"swapped":[3],"visited":[0]}},{"id":"redescend-leaf","title":"Leaf 4 is walked yet again","codeLine":5,"summary":"height keeps recursing to the bottom. Leaf 4 gets visited by the root's call and again by node 2's call, and node 4 hangs only one node deep. On a long chain a leaf is re-walked once for every ancestor above it.","state":{"tree":[1,2,3,4,null,null,5],"node":3,"visited":[0,1]}},{"id":"all-five","title":"Five nodes, the same depths over and over","codeLine":11,"summary":"Every node runs its own full height descent, so a depth measured once at the root is rediscovered at node 2, then again deeper down. Five nodes here; ten thousand nodes would re-walk the same branches ten thousand times over.","state":{"tree":[1,2,3,4,null,null,5],"node":2,"visited":[0,1,3]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function height(node) {\n    if (node == null) {\n        return 0;\n    }\n    return (1 + Math.max(height(node.left), height(node.right)));\n}\nfunction bestBend(node) {\n    if (node == null) {\n        return 0;\n    }\n    const here = height(node.left) + height(node.right);\n    const below = Math.max(bestBend(node.left), bestBend(node.right));\n    return Math.max(here, below);\n}\nreturn bestBend(root);","lineMap":{"3":2,"4":3,"5":5,"8":8,"9":9,"10":11,"11":12,"12":13,"14":15},"statementBundles":{"4":{"startLine":3,"endLine":4},"5":{"startLine":5,"endLine":7},"9":{"startLine":9,"endLine":10},"12":{"startLine":13,"endLine":14}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function height(node: TreeNode | null): number {\n    if (node == null) {\n        return 0;\n    }\n    return (1 + Math.max(height(node.left), height(node.right)));\n}\nfunction bestBend(node: TreeNode | null): number {\n    if (node == null) {\n        return 0;\n    }\n    const here = height(node.left) + height(node.right);\n    const below = Math.max(bestBend(node.left), bestBend(node.right));\n    return Math.max(here, below);\n}\nreturn bestBend(root);","lineMap":{"3":2,"4":3,"5":5,"8":8,"9":9,"10":11,"11":12,"12":13,"14":15},"statementBundles":{"4":{"startLine":3,"endLine":4},"5":{"startLine":5,"endLine":7},"9":{"startLine":9,"endLine":10},"12":{"startLine":13,"endLine":14}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int height(TreeNode node) {\n    if (node == null) {\n        return 0;\n    }\n    return (1 + Math.max(height(node.left), height(node.right)));\n}\n\nprivate static int bestBend(TreeNode node) {\n    if (node == null) {\n        return 0;\n    }\n    int here = height(node.left) + height(node.right);\n    int below = Math.max(bestBend(node.left), bestBend(node.right));\n    return Math.max(here, below);\n}\n\nreturn bestBend(root);","lineMap":{"3":2,"4":3,"5":5,"8":9,"9":10,"10":12,"11":13,"12":14,"14":17},"statementBundles":{"4":{"startLine":3,"endLine":4},"5":{"startLine":5,"endLine":8},"9":{"startLine":10,"endLine":11},"12":{"startLine":14,"endLine":15}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int Height(TreeNode node) {\n    if (node == null) {\n        return 0;\n    }\n    return 1 + Math.Max(Height(node.left), Height(node.right));\n    return 0;\n}\nint BestBend(TreeNode node) {\n    if (node == null) {\n        return 0;\n    }\n    int here = Height(node.left) + Height(node.right);\n    int below = Math.Max(BestBend(node.left), BestBend(node.right));\n    return Math.Max(here, below);\n    return 0;\n}\nreturn BestBend(root);","lineMap":{"3":2,"4":3,"5":5,"8":9,"9":10,"10":12,"11":13,"12":14,"14":17},"statementBundles":{"4":{"startLine":3,"endLine":4},"5":{"startLine":5,"endLine":8},"9":{"startLine":10,"endLine":11},"12":{"startLine":14,"endLine":16}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(TreeNode*)> height;\nfunction<int(TreeNode*)> best_bend;\n\nheight = [&]( TreeNode* node ) -> int {\n    if (!node) {\n        return 0;\n    }\n    return (1 + max(height(node->left), height(node->right)));\n};\nbest_bend = [&]( TreeNode* node ) -> int {\n    if (!node) {\n        return 0;\n    }\n    int here = height(node->left) + height(node->right);\n    int below = max(best_bend(node->left), best_bend(node->right));\n    return max(here, below);\n};\nreturn best_bend(root);","lineMap":{"3":5,"4":6,"5":8,"8":11,"9":12,"10":14,"11":15,"12":16,"14":18},"statementBundles":{"4":{"startLine":6,"endLine":7},"5":{"startLine":8,"endLine":10},"9":{"startLine":12,"endLine":13},"12":{"startLine":16,"endLine":17}}}}},"body":["For each node, call a height helper on both sides and add the two reaches. The largest such bend is the diameter."]},{"id":"waste-probe","chapter":"The obvious way","kind":"case-probe","eyebrow":"Find the waste","title":"How much work does measuring every node cost?","workspacePanel":"trace","options":[{"id":"n-squared","label":"About n descents of up to n nodes each, so roughly n^2 work","rationale":"Every node triggers a fresh height walk that can reach the bottom of the tree, so the same branches get re-descended once per ancestor. That is the n^2 blowup, and the repeated descents are pure waste because a subtree's depth never changes.","isCorrect":true},{"id":"linear","label":"One pass over n nodes, so linear n work","rationale":"A single scan is n, but each node here also runs a height descent that re-walks its subtree. Those nested descents multiply the cost well past linear.","isCorrect":false},{"id":"values-cost","label":"It re-reads the stored node values each time, and reads are the cost","rationale":"Reading a value is cheap. The expense is re-walking the same branches to rediscover depths a parent's descent already computed.","isCorrect":false}],"answer":"Roughly n^2. Each node launches a height walk that can cross most of the tree, so the same subtree depths get recomputed once per ancestor. Each node's reach down either side is fixed, so computing it once per node instead of once per ancestor removes the blowup.","summary":"Each of the n nodes runs its own height descent, and a height descent can walk most of the tree."},{"id":"path-through-node","chapter":"The idea","kind":"case-probe","eyebrow":"Find the rule","title":"How many edges does the longest path bending at the root have?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"path-through-node-state","state":{"tree":[1,2,3,4,null,null,5],"node":0,"swapped":[1,2]}}]},"options":[{"id":"left-plus-right","label":"The left reach plus the right reach, so 2 + 2 = 4","rationale":"The path climbs two edges down the left to leaf 4, comes back up through the root, and climbs two edges down the right to leaf 5. Summing how far each side reaches counts exactly those four edges.","isCorrect":true},{"id":"max-side","label":"The deeper of the two sides, so 2","rationale":"Taking only one side measures a straight path down. A path turning at the root uses both sides at once, so it spans 2 + 2 = 4.","isCorrect":false},{"id":"plus-node","label":"Left plus right plus one for the root itself, so 5","rationale":"The diameter counts edges, and the root is the bend. The two edges down each side are the whole path: 4.","isCorrect":false}],"answer":"The longest path bending at a node is how far its left side reaches plus how far its right side reaches, in edges. At the root that is 2 + 2 = 4 edges, the path 4 -> 2 -> 1 -> 3 -> 5.","summary":"One side reaches two edges to node 4, and the other reaches two edges to node 5."},{"id":"return-vs-track","chapter":"The idea","kind":"case-probe","eyebrow":"Find the rule","title":"What can the root's own parent actually build on?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"return-vs-track-state","state":{"tree":[1,2,3,4,null,null,5],"node":0,"visited":[1,2,3,6]}}]},"options":[{"id":"return-height","label":"Only the reach down one branch: a path from above leaves through a single child","rationale":"A path entering from above can follow just one branch back out of the root, so all the parent can extend is the root's deepest single-branch reach, its height. That one-sided reach is a different number from the two-sided bend of 4, which is why the bend has to be recorded somewhere else.","isCorrect":true},{"id":"return-diameter","label":"The whole bend of 4, both sides together","rationale":"A path through the higher parent cannot reuse both of the root's sides at once; it enters from above and leaves down one branch only. The bend of 4 turns inside this subtree and can never be re-extended upward, so it is finished and belongs in a separate running maximum, not handed up.","isCorrect":false},{"id":"return-both","label":"Both side reaches, 2 and 2, so the parent can re-add them","rationale":"The parent cannot route through both of the root's sides; it enters from above and leaves down a single branch. Re-adding the two sides would re-measure a bend the parent can never travel.","isCorrect":false}],"answer":"Only the reach down one branch travels upward, because a path from above can extend just a single branch out of the root. That one-sided reach is the height; here it is 3. The two-sided bend of 4 can never be re-extended by a parent, so each call RETURNS its height while the best bend is TRACKED separately in a running maximum.","summary":"The root just measured its own bend: 2 + 2 = 4 edges. Now imagine this same subtree attached under a larger parent."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which approach should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"tree":[1,2,3,4,null,null,5],"node":0}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Heights flow up, the best bend is kept aside","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"tree":[1,2,3,4,null,null,5],"node":0}}]},"body":["One depth-first walk descends to the leaves and reports back up. Each node returns its height, 1 + max(left height, right height); an empty branch reports height 0.","At every node the walk also checks left height plus right height and keeps the largest such bend it has seen in a running maximum called diameter. These two numbers can differ: at the root the returned height will be 3 while the bend is 4.","The leaves resolve first, then their parents, then the root. The returned heights climb while diameter quietly tracks the best path anywhere in the tree."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the heights","title":"Trace the heights upward","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"node-two","state":{"tree":[1,2,3,4,null,null,5],"node":1,"swapped":[3]}},{"id":"node-three","state":{"tree":[1,2,3,4,null,null,5],"node":2,"swapped":[6],"visited":[1,3]}},{"id":"root-bend","state":{"tree":[1,2,3,4,null,null,5],"node":0,"swapped":[2],"visited":[1,3,6]}}]},"beats":[{"id":"node-two","title":"Node 2 has left height 1 (leaf 4) and right height 0 (missing). What does diameter become?","summary":"Node 2's left child is leaf 4, height 1; its right branch is empty, height 0.","prompt":"Node 2 sees left height 1 and right height 0, with diameter still 0.","options":[{"id":"one","label":"1","rationale":"The bending path at node 2 is left + right = 1 + 0 = 1 edge. That beats the current diameter of 0, so diameter becomes 1.","isCorrect":true},{"id":"zero","label":"0, nothing changes","rationale":"The bend at node 2 spans 1 edge, larger than 0, so the running maximum rises to 1.","isCorrect":false},{"id":"two","label":"2","rationale":"Node 2 has only one real branch, so left + right is 1 + 0 = 1, not 2. The bend is 1.","isCorrect":false}],"answer":"1. Node 2's bend is left + right = 1 + 0 = 1 edge, which raises diameter from 0 to 1. Node 2 returns height 1 + max(1, 0) = 2 upward."},{"id":"node-three","title":"Node 3 has left height 0 (missing) and right height 1 (leaf 5). What does diameter become?","summary":"Node 2 returned height 2. Now node 3's right child is leaf 5, height 1; its left branch is empty, height 0.","prompt":"Node 3 sees left height 0 and right height 1, with diameter currently 1.","options":[{"id":"one","label":"1, no change","rationale":"Node 3's bend is left + right = 0 + 1 = 1 edge, the same as the current diameter, so the maximum stays 1.","isCorrect":true},{"id":"two","label":"2","rationale":"Node 3 has only one real branch, so its bend is 0 + 1 = 1, not 2. Diameter stays 1.","isCorrect":false},{"id":"zero","label":"0","rationale":"The bend of 1 does not lower the running maximum; it ties it. Diameter stays 1.","isCorrect":false}],"answer":"1. Node 3's bend is left + right = 0 + 1 = 1 edge, which ties the current diameter, so it stays 1. Node 3 returns height 1 + max(0, 1) = 2 upward."},{"id":"root-bend","title":"The root has left height 2 and right height 2. Height returned is 3, but what does diameter become?","summary":"Node 2 returned height 2 and node 3 returned height 2, so the root reads left height 2 and right height 2.","prompt":"The root sees left height 2 and right height 2, with diameter currently 1. Watch the two numbers diverge: the root will RETURN height 3 but its bend is something else.","options":[{"id":"four","label":"4","rationale":"The bend at the root is left + right = 2 + 2 = 4 edges, the path 4 -> 2 -> 1 -> 3 -> 5. That beats the current 1, so diameter becomes 4. Crucially, the root still RETURNS height 1 + max(2, 2) = 3, a different number: 3 is the one-sided reach it hands up, 4 is the two-sided bend it records.","isCorrect":true},{"id":"three","label":"3, same as the returned height","rationale":"This is the trap: the returned height (3) and the bend are NOT the same number. The bend uses both sides, 2 + 2 = 4, while the height uses one side, 1 + max(2, 2) = 3. Diameter becomes 4.","isCorrect":false},{"id":"two","label":"2, the deeper side only","rationale":"Taking one side measures a straight descent. The path that bends at the root adds both sides: 2 + 2 = 4.","isCorrect":false}],"answer":"4. The root's bend is left + right = 2 + 2 = 4 edges, the path 4 -> 2 -> 1 -> 3 -> 5, so diameter becomes 4. But the root RETURNS height 1 + max(2, 2) = 3. Here is the payoff: returned height 3 and bend 4 are different numbers, because a parent can extend only one branch (height 3) while the bend that turns here (4) can never be re-extended and lives in the separate diameter maximum."}]},{"id":"return-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could the helper return the bend it just measured?","workspacePanel":"trace","pitfall":"This helper keeps the diameter tracker and updates it with left + right at every node, exactly the right idea. The one slip is the last line: it returns left + right, the bend, instead of max(left, right) + 1, the height.","whyItMatters":"The number a node returns becomes its parent's left or right height, so the returned value feeds the next node's bend computation. Returning the bend instead of the height poisons every ancestor's heights: a leaf reports 0 instead of 1, so its parent's left and right both read 0, so its bend reads 0, and the tracker that should climb to 4 never moves off 0. The update line was correct; it was fed lies. Return max(left, right) + 1 so the heights flowing up stay true, and let left + right only feed the separate tracker.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def diameterOfBinaryTree(root: TreeNode | None) -> int:\n    diameter = 0\n\n    def depth(node: TreeNode | None) -> int:\n        nonlocal diameter\n        if not node:\n            return 0\n        left = depth(node.left)\n        right = depth(node.right)\n        diameter = max(diameter, left + right)\n        return left + right\n\n    depth(root)\n    return diameter","steps":[{"id":"leaf-returns-bend","title":"Leaf 4 hands up 0 instead of its height 1","codeLine":11,"summary":"Tree [1, 2, 3, 4, null, null, 5]. Leaf 4 has two empty branches, so left = 0 and right = 0. The tracker update sees 0 + 0 = 0, fine for a leaf. But the return is left + right = 0, so leaf 4 reports height 0 to its parent. The correct height of a leaf is 1.","state":{"tree":[1,2,3,4,null,null,5],"node":3}},{"id":"parent-updates-from-lie","title":"Node 2 updates its bend from a false height","codeLine":10,"summary":"Node 2 reads left = depth(leaf 4) = 0 (it should be 1) and right = 0. So its tracker update computes left + right = 0 and records nothing, even though the real bend through node 2 is 1 edge. The update rule is right; the heights it was handed are wrong.","state":{"tree":[1,2,3,4,null,null,5],"node":1,"swapped":[3]}},{"id":"root-tracker-stuck","title":"The root's bend reads 0, and diameter stays 0","codeLine":10,"summary":"Node 2 returned 0 and node 3 returned 0, so the root reads left = 0 and right = 0. Its update computes 0 + 0 = 0, so diameter never leaves 0. The true diameter is 4, the path 4 -> 2 -> 1 -> 3 -> 5, but every collapsed height starved the update line of the real numbers.","state":{"tree":[1,2,3,4,null,null,5],"node":0,"swapped":[2],"visited":[1,3,6]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let diameter = 0;\nfunction depth(node) {\n    if (node == null) {\n        return 0;\n    }\n    const left = depth(node.left);\n    const right = depth(node.right);\n    diameter = Math.max(diameter, (left + right));\n    return (left + right);\n}\ndepth(root);\nreturn diameter;","lineMap":{"2":1,"5":3,"6":3,"7":4,"8":6,"9":7,"10":8,"11":9,"13":11,"14":12},"statementBundles":{"2":{"startLine":1,"endLine":2},"7":{"startLine":4,"endLine":5},"11":{"startLine":9,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let diameter = 0;\nfunction depth(node: TreeNode | null): number {\n    if (node == null) {\n        return 0;\n    }\n    const left = depth(node.left);\n    const right = depth(node.right);\n    diameter = Math.max(diameter, (left + right));\n    return (left + right);\n}\ndepth(root);\nreturn diameter;","lineMap":{"2":1,"5":3,"6":3,"7":4,"8":6,"9":7,"10":8,"11":9,"13":11,"14":12},"statementBundles":{"2":{"startLine":1,"endLine":2},"7":{"startLine":4,"endLine":5},"11":{"startLine":9,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int depth(TreeNode node, int[] diameter) {\n    if (node == null) {\n        return 0;\n    }\n    int left = depth(node.left, diameter);\n    int right = depth(node.right, diameter);\n    diameter[0] = Math.max(diameter[0], (left + right));\n    return (left + right);\n}\n\nint[] diameter = new int[]{0};\ndepth(root, diameter);\nreturn diameter[0];","lineMap":{"2":11,"5":2,"6":2,"7":3,"8":5,"9":6,"10":7,"11":8,"13":12,"14":13},"statementBundles":{"7":{"startLine":3,"endLine":4},"11":{"startLine":8,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int diameter = 0;\nint Depth(TreeNode node) {\n    if (node == null) {\n        return 0;\n    }\n    int left = Depth(node.left);\n    int right = Depth(node.right);\n    diameter = Math.Max(diameter, left + right);\n    return left + right;\n    return 0;\n}\nDepth(root);\nreturn diameter;","lineMap":{"2":1,"5":3,"6":3,"7":4,"8":6,"9":7,"10":8,"11":9,"13":12,"14":13},"statementBundles":{"2":{"startLine":1,"endLine":2},"7":{"startLine":4,"endLine":5},"11":{"startLine":9,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(TreeNode*)> depth;\n\nint diameter = 0;\ndepth = [&]( TreeNode* node ) -> int {\n    if (!node) {\n        return 0;\n    }\n    int left = depth(node->left);\n    int right = depth(node->right);\n    diameter = max(diameter, (left + right));\n    return (left + right);\n};\ndepth(root);\nreturn diameter;","lineMap":{"2":3,"5":5,"6":5,"7":6,"8":8,"9":9,"10":10,"11":11,"13":13,"14":14},"statementBundles":{"2":{"startLine":3,"endLine":4},"7":{"startLine":6,"endLine":7},"11":{"startLine":11,"endLine":12}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"tree":[1],"node":0}}]},"body":["Returning depth upward while tracking the best bend works on a full tree, but a recursion like this tends to slip on the smallest shapes, where a node has almost nothing below it to measure.","Worth checking before coding: an empty tree with no nodes at all, a lone root with two empty branches, and a one-sided chain where the longest path never bends."]},{"id":"single-node-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What diameter does a lone root report?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-node-state","state":{"tree":[1],"node":0}}]},"options":[{"id":"zero","label":"0","rationale":"Both empty branches report height 0, so the bend is left + right = 0 + 0 = 0. One node has no edges, so its diameter is 0.","isCorrect":true},{"id":"one","label":"1","rationale":"A lone node returns height 1, but height is not the diameter. The bend across 0 and 0 is 0 edges.","isCorrect":false},{"id":"two","label":"2","rationale":"That would treat each empty branch as a real edge. Empty branches report 0, so the bend is 0.","isCorrect":false}],"answer":"0. The two empty branches report height 0, so the bend is 0 + 0 = 0 edges. The same zero base case makes an empty tree return 0 too.","summary":"The tree is a single node with two empty branches."},{"id":"skewed-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What is the diameter of a one-sided chain?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"skewed-state","state":{"tree":[1,2,null,3,null,null,null,4],"node":0}}]},"options":[{"id":"three","label":"3, the whole chain","rationale":"No node bends; at each one the right side is empty, so left + right equals just the left reach. The longest left reach spans the three edges of the chain.","isCorrect":true},{"id":"zero","label":"0, nothing bends","rationale":"A path need not bend to count. The straight chain is itself a path of 3 edges, which the running maximum captures.","isCorrect":false},{"id":"six","label":"6, doubling the chain","rationale":"There is no right branch to add, so the depths are never doubled. The path is the single chain of 3 edges.","isCorrect":false}],"answer":"3. With an empty right side at every node, each bend is just the left reach. The deepest one spans the full chain of 3 edges, and the running maximum holds it.","summary":"Every node has only a left child: 1 -> 2 -> 3 -> 4, four nodes in a straight line."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Return depth upward, but record the best left-plus-right bend in a maximum that lives outside the recursion.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"tree":[1,2,3,4,5],"node":0}}]},"body":["Keep a diameter maximum beside the recursion, starting at 0. Walk depth-first: an empty branch reports 0, and every real node measures the bend left + right against that maximum.","Each node then returns its own depth, the deeper child plus one, so a parent can extend a single branch. After the walk finishes, the recorded maximum is the answer."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the height-and-diameter recursion","eyebrow":"Code the rule","summary":"Now turn the two-questions walk into code: start the diameter tracker at 0, recurse into both children with a missing node reporting 0, update the tracker with left plus right at each node, return max(left, right) plus one upward, run the walk from the root, then return the tracker.","workspacePanel":"code","checkpoints":[{"id":"init-diameter","title":"Initialize the best diameter","description":"Start a numeric tracker at 0 because a diameter counts edges.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_recursive_zero_extremum_tracker","scope":"init-diameter","readMode":"tree-value-query-v1"}]},"commonMistakes":["Starting at 1 and counting nodes instead of edges","Returning height directly without tracking the best left-plus-right path"],"hint":"The smallest possible diameter is 0 edges.","semanticSpec":{"intent":"Create a numeric tracker for the best diameter seen so far.","doneWhen":"This step is done when the solution initializes a numeric best-diameter state to 0.","shouldFailWhen":"This step should fail if there is no numeric tracker or if the tracker starts as a node count.","roles":["diameter tracker","zero edge count"],"mustProve":["A numeric state is initialized to 0."],"mustNotAccept":["Returning subtree height without a separate best value."],"equivalentVariants":["Use a local nonlocal variable, a mutable cell, or an instance field initialized to 0."],"proofSnippets":[{"id":"py-init-diameter","language":"python","code":"def diameterOfBinaryTree(root):\n    diameter = 0"}]}},{"id":"recursive-heights","title":"Compute both child heights","description":"Use a recursive helper that returns 0 for missing nodes and recurses into both children.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"guards_and_recurses_into_child_subtrees","scope":"recursive-step","readMode":"tree-value-query-v1"}]},"commonMistakes":["Exploring only one child","Forgetting the empty-node base case"],"hint":"The helper should return the height of the subtree rooted at the current node.","semanticSpec":{"intent":"Define the height recursion over both child subtrees.","doneWhen":"This step is done when a helper guards missing nodes and obtains recursive heights from both left and right children.","shouldFailWhen":"This step should fail if only one child contributes or if the missing-node case is not guarded.","roles":["current node","left height","right height"],"mustProve":["The helper returns 0 for a missing node.","The helper recurses on both child links."],"mustNotAccept":["Using the same child for both recursive calls."],"equivalentVariants":["Store child heights in variables or inline them in later expressions."]}},{"id":"update-diameter","title":"Update with left plus right","description":"At each node, compare the best diameter with the path that uses both child heights.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"updates_recursive_child_pair_extremum","scope":"update-diameter","readMode":"tree-value-query-v1"}]},"commonMistakes":["Updating with max(left, right) instead of left + right","Adding 1 when updating the diameter and accidentally counting nodes"],"hint":"The path through a node has `left + right` edges.","semanticSpec":{"intent":"Use the pair of child heights to update the global best diameter.","doneWhen":"This step is done when the tracker is updated with a max-like comparison against left height plus right height.","shouldFailWhen":"This step should fail if the update reads only one child height or counts the current node as an extra edge.","roles":["left height","right height","diameter tracker"],"mustProve":["The update reads both captured child heights.","The tracked best value is updated through a max-like operation."],"mustNotAccept":["Using only one child height.","Returning the candidate path without tracking the best across all nodes."],"equivalentVariants":["Assign `diameter = max(diameter, left + right)` or update an equivalent mutable tracker."]}},{"id":"return-height","title":"Return height to the parent","description":"Return the deeper child height plus one so the parent can compute its own diameter candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_combined_child_extremum","scope":"return-max-plus-one","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning left + right upward","Forgetting to add one for the current node's height"],"hint":"A parent can continue through only one child branch.","semanticSpec":{"intent":"Return the current subtree height rather than the local diameter.","doneWhen":"This step is done when the helper returns max(left, right) + 1.","shouldFailWhen":"This step should fail if the helper returns left + right or omits the current node.","roles":["left height","right height","returned height"],"mustProve":["The return chooses the larger child height.","The return adds one for the current node."],"mustNotAccept":["Returning both child heights upward as a path.","Returning the tracked diameter from inside the helper."],"equivalentVariants":["Return `1 + max(left, right)` or an equivalent expression."],"proofSnippets":[{"id":"py-return-height","language":"python","code":"def diameterOfBinaryTree(root):\n    diameter = 0\n\n    def depth(node):\n        nonlocal diameter\n        if not node:\n            return 0\n        left = depth(node.left)\n        right = depth(node.right)\n        diameter = max(diameter, left + right)\n        return max(left, right) + 1"}]}},{"id":"start-dfs","title":"Run DFS from the root","description":"Start the height helper at the original root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"invokes_recursive_child_helper_with_root","scope":"start-dfs","readMode":"tree-value-query-v1"}]},"commonMistakes":["Defining the helper but never calling it","Calling the helper on a child instead of the root"],"hint":"The helper must visit the whole tree, starting from root.","semanticSpec":{"intent":"Execute the height recursion over the original tree root.","doneWhen":"This step is done when the helper is invoked with the original root.","shouldFailWhen":"This step should fail if the helper is not started at root.","roles":["root","height helper"],"mustProve":["The helper is invoked with the original root."],"mustNotAccept":["Calling the helper on a non-root object."],"equivalentVariants":["Call the DFS on root before returning the tracker."],"proofSnippets":[{"id":"py-start-dfs","language":"python","code":"def diameterOfBinaryTree(root):\n    diameter = 0\n\n    def depth(node):\n        nonlocal diameter\n        if not node:\n            return 0\n        left = depth(node.left)\n        right = depth(node.right)\n        diameter = max(diameter, left + right)\n        return max(left, right) + 1\n\n    depth(root)"}]}},{"id":"return-diameter","title":"Return the best diameter","description":"Return the best diameter found across all nodes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_recursive_extremum_tracker","scope":"return-global-max","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning the root height instead of the tracked diameter","Returning the helper result directly"],"hint":"The helper computes heights for side effects on the best diameter tracker.","semanticSpec":{"intent":"Return the tracked answer after DFS finishes.","doneWhen":"This step is done when the outer function returns the best-diameter tracker.","shouldFailWhen":"This step should fail if the function returns subtree height instead of the tracker.","roles":["diameter tracker"],"mustProve":["The final return uses the tracked diameter state."],"mustNotAccept":["Returning the helper call result directly."],"equivalentVariants":["Return the numeric tracker after the helper has visited the tree."],"proofSnippets":[{"id":"py-return-diameter","language":"python","code":"def diameterOfBinaryTree(root):\n    diameter = 0\n\n    def depth(node):\n        nonlocal diameter\n        if not node:\n            return 0\n        left = depth(node.left)\n        right = depth(node.right)\n        diameter = max(diameter, left + right)\n        return max(left, right) + 1\n\n    depth(root)\n    return diameter"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"A node returns 1 + max(left, right) so a parent can extend one branch, while the bend left + right is recorded in a separate maximum.","workspacePanel":"code","body":["Two different questions share one walk: how far a single branch reaches, which flows up as depth, and how long a path that turns at this node is, which is left + right.","Returning depth keeps each parent able to stretch one branch higher; the best bend can never be extended, so it lives outside the recursion in the diameter maximum."],"takeaways":[{"title":"Depth flows up, the bend stays put","body":"A node returns 1 + max(left, right) so a parent extends one branch, while left + right is the path that turns here and goes into a separate running maximum."},{"title":"The zero base case carries every edge case","body":"An empty branch returns 0, so an empty tree, a lone node, and a one-sided chain all fall straight out of the same base case with no extra branches."},{"title":"Count edges, never the node","body":"The bend at a node is left + right, with no + 1 for the node itself, because the diameter is measured in edges and the node marks the turn without adding an edge."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"executionStyle":"solution-method"}
