{"id":"path-sum","title":"Path Sum","difficulty":"easy","patterns":["tree-dfs"],"primaryConcept":"tree-dfs-basics","concepts":["tree-dfs-basics"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"tree","primaryParam":"root","secondaryParams":{"targetSum":{"strategy":"random-int","value":{"min":-20,"max":40}}},"sizeMetric":"node-count"},"description":"Given the root of a binary tree and an integer `targetSum`, return `true` if the tree has a root-to-leaf path whose node values sum to `targetSum`. Otherwise, return `false`.\n\nA leaf is a node with no left child and no right child.","examples":[{"input":"root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22","output":"true","explanation":"The root-to-leaf path 5 -> 4 -> 11 -> 2 sums to 22."},{"input":"root = [1,2,3], targetSum = 5","output":"false","explanation":"The path 1 -> 2 sums to 3 and the path 1 -> 3 sums to 4."},{"input":"root = [], targetSum = 0","output":"false","explanation":"An empty tree has no root-to-leaf path."}],"constraints":[{"id":"0-number-of-nodes-5000","text":"0 <= number of nodes <= 5000","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":0,"max":5000}},{"id":"1000-node-val-1000","text":"-1000 <= Node.val <= 1000","check":{"kind":"valueRange","target":"root","selector":"treeValues","min":-1000,"max":1000}},{"id":"10-6-targetsum-10-6","text":"-10^6 <= targetSum <= 10^6","check":{"kind":"valueRange","target":"targetSum","selector":"value","min":-1000000,"max":1000000}}],"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 hasPathSum(self, root: TreeNode | None, targetSum: int) -> bool:\n        # Your code here\n        pass","functionName":"hasPathSum","testCases":[{"id":"1","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":5,"left":{"__type__":"TreeNode","__id__":"tree-1","val":4,"left":{"__type__":"TreeNode","__id__":"tree-3","val":11,"left":{"__type__":"TreeNode","__id__":"tree-7","val":7,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-8","val":2,"left":null,"right":null}},"right":null},"right":{"__type__":"TreeNode","__id__":"tree-2","val":8,"left":{"__type__":"TreeNode","__id__":"tree-5","val":13,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-6","val":4,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-10","val":1,"left":null,"right":null}}}},"targetSum":22},"expected":true,"description":"Canonical positive example."},{"id":"2","input":{"root":{"__type__":"TreeNode","__id__":"tree-a","val":1,"left":{"__type__":"TreeNode","__id__":"tree-b","val":2,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-c","val":3,"left":null,"right":null}},"targetSum":5},"expected":false,"description":"No root-to-leaf path reaches the target."},{"id":"3","input":{"root":null,"targetSum":0},"expected":false,"description":"Empty tree has no path."},{"id":"4","input":{"root":{"__type__":"TreeNode","__id__":"single","val":-2,"left":null,"right":null},"targetSum":-2},"expected":true,"description":"Single-node tree can satisfy the target."},{"id":"5","input":{"root":{"__type__":"TreeNode","__id__":"neg-0","val":-2,"left":null,"right":{"__type__":"TreeNode","__id__":"neg-1","val":-3,"left":null,"right":null}},"targetSum":-5},"expected":true,"description":"Negative values are handled normally."},{"id":"6","input":{"root":{"__type__":"TreeNode","__id__":"internal-0","val":1,"left":{"__type__":"TreeNode","__id__":"internal-1","val":2,"left":{"__type__":"TreeNode","__id__":"internal-2","val":3,"left":null,"right":null},"right":null},"right":null},"targetSum":3},"expected":false,"description":"A matching prefix is not enough if it does not end at a leaf."},{"id":"h1","input":{"root":{"__type__":"TreeNode","__id__":"h1-0","val":3,"left":{"__type__":"TreeNode","__id__":"h1-1","val":9,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"h1-2","val":20,"left":{"__type__":"TreeNode","__id__":"h1-3","val":15,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"h1-4","val":7,"left":null,"right":null}}},"targetSum":31},"expected":false,"description":"Target is close to an internal partial sum but no leaf path matches."},{"id":"h2","input":{"root":{"__type__":"TreeNode","__id__":"h2-0","val":0,"left":{"__type__":"TreeNode","__id__":"h2-1","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"h2-2","val":0,"left":null,"right":{"__type__":"TreeNode","__id__":"h2-3","val":0,"left":null,"right":null}}},"targetSum":0},"expected":true,"description":"Zero-valued path reaches a leaf."},{"id":"h3","input":{"root":{"__type__":"TreeNode","__id__":"h3-0","val":-2,"left":null,"right":{"__type__":"TreeNode","__id__":"h3-1","val":-3,"left":null,"right":null}},"targetSum":-5},"expected":true,"description":"Negative path sums work the same way as positive ones."},{"id":"h4","input":{"root":{"__type__":"TreeNode","__id__":"h4-0","val":-2,"left":null,"right":{"__type__":"TreeNode","__id__":"h4-1","val":-3,"left":null,"right":null}},"targetSum":-2},"expected":false,"description":"A partial sum that matches before a leaf should still be rejected."}],"hints":[{"level":1,"content":"A valid path must start at the root and end at a leaf."},{"level":2,"content":"Carry the running sum as recursion descends through the tree."},{"level":3,"content":"Only compare the running sum to targetSum after confirming the current node is a leaf."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"dfs-carry","name":"DFS carrying the running sum","summary":"Walk each branch from the root, adding node values into one running total, and check it only when you reach a leaf.","decisionReason":"One number rides down each branch and is compared only at leaves, so the whole tree is answered in a single O(n) pass with stack depth O(h).","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["Runs in O(n) time and uses O(h) space for the recursion stack."],"isOptimal":true},{"id":"collect-all-paths","name":"Collect every path, then sum","summary":"Build the full list of node values for every root-to-leaf path, then add up each finished list to test it against targetSum.","decisionReason":"Storing every path keeps each one whole when only its total matters, so it copies up to O(h) values per path and holds O(n*h) of them at once for an answer that needs a single number.","complexity":{"time":"O(n*h)","space":"O(n*h)"},"tradeoffs":["Runs in O(n*h) time and keeps O(n*h) values of stored paths."],"isOptimal":false}]},"codingCheckpoints":[{"id":"dfs-function","title":"Define DFS helper","description":"Create a recursive helper that visits a node with the current branch sum.","commonMistakes":["Trying to use a global sum for all branches","Not passing the carried sum into recursive calls"],"hint":"The helper needs the current node and the running sum for that branch.","semanticSpec":{"intent":"Define a recursive helper that carries branch state while traversing the tree.","doneWhen":"The code has a DFS helper that can recurse on tree children with carried path/sum state.","shouldFailWhen":"This step should fail if no recursive tree helper is defined.","roles":["current node","running sum","recursive helper"],"mustProve":["A helper function recursively processes tree nodes.","The helper has access to a carried sum or equivalent branch state."],"mustNotAccept":["A loop that never descends through child links.","A helper that does not carry any branch state."],"equivalentVariants":["Use a nested DFS helper or a separate recursive method."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"defines_recursive_path_helper","scope":"dfs-function","readMode":"tree-value-query-v1"}]}},{"id":"null-check","title":"Stop on null nodes","description":"Return immediately when DFS reaches a missing child.","commonMistakes":["Reading node.val before checking for null","Treating a missing child as a valid leaf path"],"hint":"The null guard should happen before any node fields are read.","semanticSpec":{"intent":"Prevent recursion from processing missing child links as real nodes.","doneWhen":"The DFS helper checks for a null node and returns before accessing node fields.","shouldFailWhen":"This step should fail if missing nodes can fall through into the path logic.","roles":["current node","null guard","recursive exit"],"mustProve":["The helper tests whether the current node is absent.","The absent-node branch returns immediately."],"mustNotAccept":["Checking children or value before the null guard.","Counting null nodes as leaves."],"equivalentVariants":["Use `if not node: return` or an equivalent null check."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"guards_empty_recursive_path_case","scope":"null-check","readMode":"tree-value-query-v1"}]}},{"id":"update-path-sum","title":"Fold the node into the running sum","description":"On entering a node, record it on the current branch: append it to the shared path list and add its value to the running total, before deciding anything about this node.","commonMistakes":["Adding the node value after the leaf check","Sharing one mutable sum across sibling branches"],"hint":"Add node.val to the carried total before the leaf check, so the comparison sees the completed branch sum.","semanticSpec":{"intent":"Carry the current node's contribution into the branch state before leaf evaluation.","doneWhen":"The DFS frame appends or records the node on the current branch and adds node.val to the running sum.","shouldFailWhen":"This step should fail if the current node value is not folded into the branch sum.","roles":["current node value","current path","running sum"],"mustProve":["The current node value is added to the carried sum.","The current branch path state is updated for visualization/backtracking."],"mustNotAccept":["Comparing the target before including the current node.","Updating a shared sum without preserving branch independence."],"equivalentVariants":["Use `current_sum + node.val` in recursive calls or update a local carried variable before recursing."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"updates_recursive_path_carry_state","scope":"update-path-sum","readMode":"tree-value-query-v1"}]}},{"id":"leaf-check","title":"Check leaf target","description":"Only mark success when a leaf path's completed sum equals targetSum.","commonMistakes":["Returning true for an internal prefix sum","Checking only one child when deciding leaf status"],"hint":"A valid path ends where both child links are missing.","semanticSpec":{"intent":"Accept a path only when the current node is a leaf and the completed branch sum equals targetSum.","doneWhen":"The DFS checks both child links are absent and compares the updated running sum to targetSum before marking success.","shouldFailWhen":"This step should fail if the sum check is not restricted to leaf nodes.","roles":["leaf test","running sum","target sum","success state"],"mustProve":["The code checks that the current node has no left or right child.","The updated sum is compared to targetSum on that leaf branch.","A success state is recorded only after both conditions hold."],"mustNotAccept":["Accepting internal nodes whose prefix sum equals targetSum.","Marking success without comparing the running sum to targetSum."],"equivalentVariants":["Return true directly from the leaf branch or update a tracked boolean success state."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"checks_leaf_terminal_path","scope":"leaf-check","readMode":"tree-value-query-v1"}]}},{"id":"recursive-calls","title":"Recurse into children","description":"Explore both left and right children with the updated branch sum.","commonMistakes":["Only checking one side of the tree","Resetting the sum before child recursion"],"hint":"Both child calls should receive the same updated sum for this node.","semanticSpec":{"intent":"Continue the carried branch search into both child subtrees.","doneWhen":"DFS recursively calls the left and right child links with the updated branch state.","shouldFailWhen":"This step should fail if a child side is skipped or the carry state is not threaded.","roles":["left child","right child","running sum","recursive call"],"mustProve":["The helper recurses into both child links.","The carried sum is passed into child recursion."],"mustNotAccept":["Calling the same child twice.","Dropping the carried state in recursive calls."],"equivalentVariants":["Use two recursive calls or combine them in a boolean expression."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"recurses_into_child_subtrees_with_carry","scope":"recursive-calls","readMode":"tree-value-query-v1"}]}},{"id":"backtrack","title":"Remove the node from the path on the way out","description":"After both child calls return, drop the current node from the shared path list so the branch state is restored for the node's siblings, and have the finished traversal report whether any leaf matched.","commonMistakes":["Never removing the node, so sibling branches inherit stale path values","Removing the node before exploring its children"],"hint":"The append you made on the way in has to be undone on the way out: pop the current node after both recursive calls, then return the recorded result.","semanticSpec":{"intent":"Restore the mutable branch path after exploring the current node's subtree.","doneWhen":"The DFS removes the current node from the path after the recursive child calls and the completed traversal returns the accumulated path-sum result.","shouldFailWhen":"This step should fail if the path append is never cleaned up.","roles":["current path","backtracking cleanup"],"mustProve":["The mutable path state is cleaned after child exploration.","The completed traversal returns whether a valid root-to-leaf path was found."],"mustNotAccept":["Never removing nodes from the current path.","Clearing the whole path before child recursion."],"equivalentVariants":["Use `path.pop()` or an equivalent branch-state cleanup."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"cleans_mutable_path_state","scope":"backtrack","readMode":"tree-value-query-v1"}]}}],"slides":[{"id":"read-the-signal","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Does any root-to-leaf path hit the target?","workspacePanel":"problem","body":["You get a binary tree and a number targetSum. Return true if some path from the root straight down to a leaf has node values that add up to targetSum, and false otherwise.","A leaf is a node with no children. Here targetSum is 22, and the path 5 -> 4 -> 11 -> 2 adds to 22, so the answer is true.","A path has to start at the root and stop at a leaf. The branch 5 -> 4 -> 11 -> 7 adds to 27, so it does not count."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Collect every path, then sum each one","summary":"The trace finds the matching path, but each leaf rebuilds the total from the stored path.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def dfs(node: TreeNode | None, path: list[int], targetSum: int) -> bool:\n    if not node:\n        return False\n    path.append(node.val)\n    if not node.left and not node.right:\n        total = 0\n        for v in path:\n            total += v\n        path.pop()\n        return total == targetSum\n    found = dfs(node.left, path, targetSum) or dfs(node.right, path, targetSum)\n    path.pop()\n    return found","steps":[{"id":"build-first","title":"Build the first full path","codeLine":4,"summary":"Descend 5, 4, 11, 7 to a leaf, growing path one node at a time: [5], [5,4], [5,4,11], [5,4,11,7]. The whole list of ancestors is held.","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":7,"visited":[0,1,3]}},{"id":"sum-first-leaf","title":"Re-add the whole path at the leaf","codeLine":8,"summary":"At leaf 7 the loop walks every stored value, 5 + 4 + 11 + 7, from scratch to get 27. Four additions for one leaf, and the same ancestors will be re-added for its sibling.","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":7,"visited":[0,1,3]}},{"id":"sum-sibling-leaf","title":"The shared prefix is summed again","codeLine":8,"summary":"For the sibling leaf 2 the loop re-adds 5 + 4 + 11 before reaching 2. The same three ancestors are summed a second time. Each leaf re-walks its full path, so the work is O(n * h).","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":8,"visited":[0,1,3,7]}},{"id":"sum-each","title":"Each leaf compares its re-added total","codeLine":10,"summary":"Only at a leaf is the total compared to 22. [5,4,11,2] re-adds to 22, so the result is true, after re-summing whole paths at every leaf the search reached.","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":8,"visited":[0,1,3,7,8,2,5,6,14]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (node == null) {\n    return false;\n}\npath.push(node.val);\nif (!node.left && !node.right) {\n    let total = 0;\n    for (const v of path) {\n        total += v;\n    }\n    path.pop();\n    return (total === targetSum);\n}\nconst found = dfs(node.left, path, targetSum) || dfs(node.right, path, targetSum);\npath.pop();\nreturn found;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12}},"alternateStyles":{"close-to-source":{"code":"if (node == null) {\n    return false;\n}\npath.push(node.val);\nif (!node.left && !node.right) {\n    let total = 0;\n    for (const v of path) {\n        total += v;\n    }\n    path.pop();\n    return (total === targetSum);\n}\nconst found = dfs(node.left, path, targetSum) || dfs(node.right, path, targetSum);\nconst poppedValue = path.pop();\nif (poppedValue === undefined) throw new Error(\"IndexError\");\nreturn found;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":16},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"12":{"startLine":14,"endLine":15}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (node == null) {\n    return false;\n}\npath.push(node.val);\nif (!node.left && !node.right) {\n    let total = 0;\n    for (const v of path) {\n        total += v;\n    }\n    path.pop();\n    return (total === targetSum);\n}\nconst found = dfs(node.left, path, targetSum) || dfs(node.right, path, targetSum);\npath.pop();\nreturn found;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12}},"alternateStyles":{"close-to-source":{"code":"if (node == null) {\n    return false;\n}\npath.push(node.val);\nif (!node.left && !node.right) {\n    let total = 0;\n    for (const v of path) {\n        total += v;\n    }\n    path.pop();\n    return (total === targetSum);\n}\nconst found = dfs(node.left, path, targetSum) || dfs(node.right, path, targetSum);\nconst poppedValue = path.pop();\nif (poppedValue === undefined) throw new Error(\"IndexError\");\nreturn found;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":16},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"12":{"startLine":14,"endLine":15}}}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (node == null) {\n    return false;\n}\npath.Add(node.val);\nif (node.left == null && node.right == null) {\n    int total = 0;\n    foreach (int v in path) {\n        total += v;\n    }\n    path.RemoveAt(path.Count - 1);\n    return total == targetSum;\n}\nbool found = Dfs(node.left, path, targetSum) || Dfs(node.right, path, targetSum);\npath.RemoveAt(path.Count - 1);\nreturn found;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (!node) {\n    return false;\n}\npath.push_back(node->val);\nif ((!node->left && !node->right)) {\n    int total = 0;\n    for (int v : path) {\n        total += v;\n    }\n    path.pop_back();\n    return (total == target_sum);\n}\nbool found = dfs(node->left, path, target_sum) || dfs(node->right, path, target_sum);\npath.pop_back();\nreturn found;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (node == null) {\n    return false;\n}\npath.add(node.val);\nif ((!(node.left != null) && !(node.right != null))) {\n    int total = 0;\n    for (Integer v : path) {\n        total += v;\n    }\n    path.remove(path.size() - 1);\n    return total == targetSum;\n}\nboolean found = dfs(node.left, path, targetSum) || dfs(node.right, path, targetSum);\npath.remove(path.size() - 1);\nreturn found;","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":15},"statementBundles":{"3":{"startLine":2,"endLine":3},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12}}}}}},{"id":"waste-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the waste","title":"What part of each path actually decides the answer?","summary":"Every leaf re-walks its whole path to add it up, and only the final total is tested.","workspacePanel":"trace","options":[{"id":"just-total","label":"Only the total; the individual values never need re-reading","rationale":"The test is whether the sum equals targetSum. Re-adding the full path at every leaf is what makes this O(n * h), yet a single running total updated once per node would give the same number for O(1) work per step.","isCorrect":true},{"id":"whole-list","label":"The whole ordered list, to reconstruct the path","rationale":"The problem only asks true or false, not which path matched, so the ordered values are never inspected. Re-summing the full list at each leaf is the wasted O(n * h) work.","isCorrect":false},{"id":"last-value","label":"Only the last value, the leaf","rationale":"The leaf alone cannot tell you the path total. The needed value is the accumulated branch sum, updated once per node.","isCorrect":false}],"answer":"Only the total. The check is sum == targetSum, so re-walking the whole path at every leaf is dead weight: O(n * h) of re-summing for an answer that needs one number. Carry a single running total down each branch and update it once per node instead."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Carry one total down, or store every path and sum it?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":0}}]}},{"id":"carry-state","chapter":"The idea","kind":"case-probe","eyebrow":"Find the state","title":"Descending into a child, what single value lets it judge its own paths?","summary":"From node 4, the search steps down into node 11, which sits below 5 and 4 in the tree.","workspacePanel":"visualizer","options":[{"id":"running-sum","label":"The sum of the values above it, so far 5 + 4 = 9","rationale":"Hand each child the running total of the branch above it. Node 11 adds its own 11 to reach 20, and any leaf below only has to finish that total. No node ever needs to look back up.","isCorrect":true},{"id":"parent-value","label":"The value of the node directly above it, 4","rationale":"A single parent value loses everything higher up. Node 11 would see 4 but not the 5 above it, so it could never know the branch total. The full accumulated sum has to ride down.","isCorrect":false},{"id":"depth","label":"How many nodes are above it","rationale":"The count of ancestors says nothing about their values. Path Sum compares totals, not lengths, so depth alone cannot judge a path.","isCorrect":false}],"answer":"The running sum of the branch above. Pass 9 into node 11; it adds its value to make 20 and carries that down. Each node only needs the total so far, never the nodes themselves. (Carrying the remaining target instead, targetSum minus 9, is the same idea inverted and works just as well; we use the running total so the visual grows with the path.)","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":3,"visited":[0,1]}}]}},{"id":"when-valid","chapter":"The idea","kind":"case-probe","eyebrow":"Find the rule","title":"A running total equals targetSum at node 11. Is that a valid answer?","summary":"Suppose targetSum were 20. At node 11 the running total is exactly 20, but 11 still has two children below it.","workspacePanel":"visualizer","options":[{"id":"only-leaf","label":"No, the path through 11 is not finished yet","rationale":"A valid path runs all the way down until the branch ends. At node 11 the path still has nodes below it, so its total of 20 is only the current prefix. The search has to keep going before any total can count.","isCorrect":true},{"id":"any-match","label":"Yes, a matching total anywhere means success","rationale":"Stopping at the first match accepts an unfinished path. The problem requires the sum to land at the end of a full root-to-leaf branch, so a mid-branch match must keep descending.","isCorrect":false},{"id":"largest-prefix","label":"Yes, 20 is the largest prefix on this branch, so it is the path total","rationale":"There is no largest prefix to settle on; the total keeps changing as the branch grows past 11 down to its leaves. Only the value at the node where the branch ends is the path total, and 11 is not that node.","isCorrect":false}],"answer":"No. Node 11 still has nodes below it, so its total is only a prefix of a longer path. A total can only count once the branch has run all the way to its end, a node with no children.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":3,"visited":[0,1]}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Carry the total down, judge it at the leaves","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":0}}]},"body":["Start at the root with the running total 0. Each node adds its value and passes the new total to both children.","Only at a leaf does the total get compared to targetSum. Below, the search descends the left branch first: 5, then 4, then 11.","When a branch dead-ends without matching, the search backs up and tries the sibling with the same total from the shared ancestor."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the totals","title":"Trace the search for targetSum = 22","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"at-11","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":3,"visited":[0,1]}},{"id":"leaf-7","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":7,"visited":[0,1,3]}},{"id":"leaf-2","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":8,"visited":[0,1,3,7]}}]},"beats":[{"id":"at-11","title":"The total reaches 20 at node 11. What does the search do here?","summary":"Node 11 has children 7 and 2 below it.","prompt":"Running total is 5 + 4 + 11 = 20 at node 11.","options":[{"id":"descend","label":"Keep descending; 11 is not a leaf","rationale":"Node 11 still has children, so its total of 20 is a prefix. The search carries 20 into each child and only tests the total when it reaches a leaf.","isCorrect":true},{"id":"compare-now","label":"Compare 20 to 22 and stop this branch","rationale":"A mismatch at an internal node means nothing, the path is not finished. Only a leaf total can be ruled in or out.","isCorrect":false}],"answer":"20 is a prefix at an internal node, so the search descends, carrying 20 into both children."},{"id":"leaf-7","title":"Leaf 7 finishes its path at total 27. Accept it?","summary":"Node 7 has no children, so this path is complete.","prompt":"At leaf 7 the running total is 20 + 7 = 27, and targetSum is 22.","options":[{"id":"reject","label":"No, 27 does not equal 22; back up and try the sibling","rationale":"This is a completed leaf path, so its total is final: 27 misses 22. The search backtracks to node 11 and tries its other child with the same total, 20.","isCorrect":true},{"id":"accept","label":"Yes, a leaf was reached","rationale":"Reaching a leaf is only half the test. The total there must also equal targetSum, and 27 does not, so this path fails.","isCorrect":false}],"answer":"27 is a finished leaf total and misses 22, so the path fails. The search returns to 11 and tries node 2 with total 20."},{"id":"leaf-2","title":"Leaf 2 matches. Does the search keep exploring the 8 branch?","summary":"The total at this leaf reaches the target, with the right subtree still unvisited.","prompt":"Leaf 2 has just finished its path.","options":[{"id":"true","label":"No; one matching leaf path settles the answer as true","rationale":"The question is only whether some path exists. The instant one leaf path reaches targetSum the answer is true, so the unvisited 8 branch can never change it and the search can stop.","isCorrect":true},{"id":"keep-going","label":"Yes; every leaf has to be checked before answering","rationale":"A second match would not change a true that already holds. Exhausting the tree is only needed to prove false, never to confirm an existence answer already found.","isCorrect":false}],"answer":"No. One matching leaf path is enough for an existence answer, so the search returns true without touching the 8 branch."}]},{"id":"prefix-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Is a node with no left child already a leaf?","summary":"Once you gate the match on a leaf, the leaf test still has to be right. Checking only `not node.left` looks like enough, and on a tree where every node missing a left child also misses its right one, every test passes. But a node can have no left child and still carry a right one. Watch it judge a tree where it should say false.","workspacePanel":"trace","pitfall":"The check below treats any node with no left child as a leaf, ignoring whether a right child still hangs below it.","whyItMatters":"A leaf has no left child and no right child. Here -2 has no left child but does have a right child -3, so it is not a leaf. The one-sided test fires at -2, where the running total is exactly targetSum -2, and wrongly returns true. The real path -2 -> -3 sums to -5, so the answer is false. Test both child links: accept only when the node has no left and no right child.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def dfs(node: TreeNode | None, current_sum: int, target: int) -> bool:\n    if not node:\n        return False\n    current_sum += node.val\n    if not node.left and current_sum == target:\n        return True\n    return dfs(node.left, current_sum, target) or dfs(node.right, current_sum, target)","steps":[{"id":"at-root","title":"targetSum is -2 on this two-node tree","codeLine":4,"summary":"The tree is -2 with a single right child -3. The only root-to-leaf path is -2 -> -3, which sums to -5, so the answer should be false. The running total at the root is -2.","state":{"tree":[-2,null,-3],"node":0}},{"id":"one-sided-leaf","title":"The root has no left child, so the test calls it a leaf","codeLine":5,"summary":"`not node.left` is true at -2, and the total -2 equals targetSum. The test fires here, even though -2 still has a right child -3 hanging below it.","state":{"tree":[-2,null,-3],"node":0,"visited":[0]}},{"id":"wrong-true","title":"It returns true at a node that is not a leaf","codeLine":6,"summary":"Success is returned before reaching the real leaf -3. The completed path -2 -> -3 sums to -5, not -2, so the real answer is false.","state":{"tree":[-2,null,-3],"node":0,"visited":[0]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (node == null) {\n    return false;\n}\ncurrentSum += node.val;\nif (!node.left && currentSum === target) {\n    return true;\n}\nreturn (dfs(node.left, currentSum, target) || dfs(node.right, currentSum, target));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":8},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":7}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (node == null) {\n    return false;\n}\ncurrentSum += node.val;\nif (!node.left && currentSum === target) {\n    return true;\n}\nreturn (dfs(node.left, currentSum, target) || dfs(node.right, currentSum, target));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":8},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":7}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (node == null) {\n    return false;\n}\ncurrentSum += node.val;\nif (node.left == null && currentSum == target) {\n    return true;\n}\nreturn Dfs(node.left, currentSum, target) || Dfs(node.right, currentSum, target);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":8},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":7}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (!node) {\n    return false;\n}\ncurrent_sum += node->val;\nif ((!node->left && current_sum == target)) {\n    return true;\n}\nreturn (dfs(node->left, current_sum, target) || dfs(node->right, current_sum, target));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":8},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":7}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (node == null) {\n    return false;\n}\ncurrentSum += node.val;\nif ((!(node.left != null) && currentSum == target)) {\n    return true;\n}\nreturn (dfs(node.left, currentSum, target) || dfs(node.right, currentSum, target));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":8},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":7}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Carrying one total and testing it only at leaves held for the full tree. A leaf-gated recursion is worth pressing on the smallest shapes and on values that do not behave like a growing count.","Three inputs are worth probing before coding: an empty tree, a tree of a single node, and a branch that contains negative values."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":0}}]}},{"id":"empty-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"When recursion steps into a missing child, what should it return?","summary":"Node -2 has a right child -3 and no left child, and the search still recurses into that empty left side. targetSum is 0.","workspacePanel":"visualizer","options":[{"id":"false","label":"false; recursion has nothing to visit","rationale":"A null node is not a leaf and starts no path, so nothing under it can ever match. Returning false lets recursion fold the empty side away. The same null base case handles an entirely empty tree, where the very first call is null and the answer is false even for targetSum 0.","isCorrect":true},{"id":"true-zero","label":"true; an empty side contributes 0, which matches targetSum 0","rationale":"There is no node and no leaf here, only the absence of one. An empty branch never reaches a leaf, so it cannot succeed regardless of targetSum, including 0.","isCorrect":false}],"answer":"false. A null node has no path to complete, so it reports false and the empty side folds away. Run the same rule at the top and an empty tree returns false too, even when targetSum is 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"null-child","state":{"tree":[-2,null,-3],"node":0}}]}},{"id":"single-node-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"For a lone root of value -2 with targetSum -2, what is returned?","summary":"The tree is one node with value -2, and targetSum is -2.","workspacePanel":"visualizer","options":[{"id":"true","label":"true; the root is a leaf and its total equals targetSum","rationale":"A node with no children is a leaf, so the root is the whole path. Its running total is -2, which equals targetSum, so the leaf test succeeds and the answer is true.","isCorrect":true},{"id":"false-not-leaf","label":"false; one node is too small to be a path","rationale":"A single node with no children is a complete root-to-leaf path of length one. The leaf test applies to it directly, so it can match.","isCorrect":false}],"answer":"true. The lone root has no children, so it is a leaf. Its total -2 equals targetSum, so the path matches.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single","state":{"tree":[-2],"node":0}}]}},{"id":"negative-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"With negatives, can the search prune a branch once the total overshoots targetSum?","summary":"On the branch 5 -> -3 with targetSum 2, the total at node 5 has already passed the target before reaching the next node.","workspacePanel":"visualizer","options":[{"id":"no-prune","label":"No; the total can move either way, so every leaf must be reached","rationale":"The total at node 5 is 5, an overshoot, but the next node is -3, which pulls it back to 2 exactly at the leaf. A prefix that has passed the target can still finish on it, so no overshoot lets you prune. Carry the exact total to each leaf.","isCorrect":true},{"id":"prune","label":"Yes; once the total passes targetSum the branch cannot match","rationale":"That only holds when values are all positive and the total just grows. A negative node can bring an overshooting total back to targetSum at a deeper leaf, so cutting early would miss the 5 -> -3 path here.","isCorrect":false}],"answer":"No. The total at 5 overshoots to 5, but -3 brings it back to 2 at the leaf, which matches targetSum. The invariant is just the exact running total compared at each leaf, with no early pruning.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"overshoot","state":{"tree":[5,null,-3],"node":0}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The success test fires only where both children are absent.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"tree":[5,4,8,11,null,13,4,7,2,null,null,null,null,null,1],"node":0}}]},"body":["Recurse from the root, recording each node on a shared path as you enter it and folding its value into the running total. A missing node ends its branch and reports nothing, so guard for it first.","At a real node, check for success only when it is a leaf and the total has reached targetSum. Otherwise recurse into both children, then remove the node from the path on the way out so a sibling branch starts clean. Let either side report a match."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the carry-down search","eyebrow":"Code the rule","summary":"Define the DFS helper, stop on null nodes, fold node.val into the running sum, test targetSum only at leaves, recurse into both children, and restore the path before returning.","workspacePanel":"code","checkpoints":[{"id":"dfs-function","title":"Define DFS helper","description":"Create a recursive helper that visits a node with the current branch sum.","commonMistakes":["Trying to use a global sum for all branches","Not passing the carried sum into recursive calls"],"hint":"The helper needs the current node and the running sum for that branch.","semanticSpec":{"intent":"Define a recursive helper that carries branch state while traversing the tree.","doneWhen":"The code has a DFS helper that can recurse on tree children with carried path/sum state.","shouldFailWhen":"This step should fail if no recursive tree helper is defined.","roles":["current node","running sum","recursive helper"],"mustProve":["A helper function recursively processes tree nodes.","The helper has access to a carried sum or equivalent branch state."],"mustNotAccept":["A loop that never descends through child links.","A helper that does not carry any branch state."],"equivalentVariants":["Use a nested DFS helper or a separate recursive method."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"defines_recursive_path_helper","scope":"dfs-function","readMode":"tree-value-query-v1"}]}},{"id":"null-check","title":"Stop on null nodes","description":"Return immediately when DFS reaches a missing child.","commonMistakes":["Reading node.val before checking for null","Treating a missing child as a valid leaf path"],"hint":"The null guard should happen before any node fields are read.","semanticSpec":{"intent":"Prevent recursion from processing missing child links as real nodes.","doneWhen":"The DFS helper checks for a null node and returns before accessing node fields.","shouldFailWhen":"This step should fail if missing nodes can fall through into the path logic.","roles":["current node","null guard","recursive exit"],"mustProve":["The helper tests whether the current node is absent.","The absent-node branch returns immediately."],"mustNotAccept":["Checking children or value before the null guard.","Counting null nodes as leaves."],"equivalentVariants":["Use `if not node: return` or an equivalent null check."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"guards_empty_recursive_path_case","scope":"null-check","readMode":"tree-value-query-v1"}]}},{"id":"update-path-sum","title":"Fold the node into the running sum","description":"On entering a node, record it on the current branch: append it to the shared path list and add its value to the running total, before deciding anything about this node.","commonMistakes":["Adding the node value after the leaf check","Sharing one mutable sum across sibling branches"],"hint":"Add node.val to the carried total before the leaf check, so the comparison sees the completed branch sum.","semanticSpec":{"intent":"Carry the current node's contribution into the branch state before leaf evaluation.","doneWhen":"The DFS frame appends or records the node on the current branch and adds node.val to the running sum.","shouldFailWhen":"This step should fail if the current node value is not folded into the branch sum.","roles":["current node value","current path","running sum"],"mustProve":["The current node value is added to the carried sum.","The current branch path state is updated for visualization/backtracking."],"mustNotAccept":["Comparing the target before including the current node.","Updating a shared sum without preserving branch independence."],"equivalentVariants":["Use `current_sum + node.val` in recursive calls or update a local carried variable before recursing."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"updates_recursive_path_carry_state","scope":"update-path-sum","readMode":"tree-value-query-v1"}]}},{"id":"leaf-check","title":"Check leaf target","description":"Only mark success when a leaf path's completed sum equals targetSum.","commonMistakes":["Returning true for an internal prefix sum","Checking only one child when deciding leaf status"],"hint":"A valid path ends where both child links are missing.","semanticSpec":{"intent":"Accept a path only when the current node is a leaf and the completed branch sum equals targetSum.","doneWhen":"The DFS checks both child links are absent and compares the updated running sum to targetSum before marking success.","shouldFailWhen":"This step should fail if the sum check is not restricted to leaf nodes.","roles":["leaf test","running sum","target sum","success state"],"mustProve":["The code checks that the current node has no left or right child.","The updated sum is compared to targetSum on that leaf branch.","A success state is recorded only after both conditions hold."],"mustNotAccept":["Accepting internal nodes whose prefix sum equals targetSum.","Marking success without comparing the running sum to targetSum."],"equivalentVariants":["Return true directly from the leaf branch or update a tracked boolean success state."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"checks_leaf_terminal_path","scope":"leaf-check","readMode":"tree-value-query-v1"}]}},{"id":"recursive-calls","title":"Recurse into children","description":"Explore both left and right children with the updated branch sum.","commonMistakes":["Only checking one side of the tree","Resetting the sum before child recursion"],"hint":"Both child calls should receive the same updated sum for this node.","semanticSpec":{"intent":"Continue the carried branch search into both child subtrees.","doneWhen":"DFS recursively calls the left and right child links with the updated branch state.","shouldFailWhen":"This step should fail if a child side is skipped or the carry state is not threaded.","roles":["left child","right child","running sum","recursive call"],"mustProve":["The helper recurses into both child links.","The carried sum is passed into child recursion."],"mustNotAccept":["Calling the same child twice.","Dropping the carried state in recursive calls."],"equivalentVariants":["Use two recursive calls or combine them in a boolean expression."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"recurses_into_child_subtrees_with_carry","scope":"recursive-calls","readMode":"tree-value-query-v1"}]}},{"id":"backtrack","title":"Remove the node from the path on the way out","description":"After both child calls return, drop the current node from the shared path list so the branch state is restored for the node's siblings, and have the finished traversal report whether any leaf matched.","commonMistakes":["Never removing the node, so sibling branches inherit stale path values","Removing the node before exploring its children"],"hint":"The append you made on the way in has to be undone on the way out: pop the current node after both recursive calls, then return the recorded result.","semanticSpec":{"intent":"Restore the mutable branch path after exploring the current node's subtree.","doneWhen":"The DFS removes the current node from the path after the recursive child calls and the completed traversal returns the accumulated path-sum result.","shouldFailWhen":"This step should fail if the path append is never cleaned up.","roles":["current path","backtracking cleanup"],"mustProve":["The mutable path state is cleaned after child exploration.","The completed traversal returns whether a valid root-to-leaf path was found."],"mustNotAccept":["Never removing nodes from the current path.","Clearing the whole path before child recursion."],"equivalentVariants":["Use `path.pop()` or an equivalent branch-state cleanup."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"cleans_mutable_path_state","scope":"backtrack","readMode":"tree-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Carry one running total down each branch and test it against targetSum only at a leaf.","workspacePanel":"code","body":["The answer falls out of one root-to-leaf pass: a single running total rides down each branch, and the brute force's stored lists are gone. The path list you keep alongside it is just the visited branch, restored with a pop as each node returns so a sibling starts clean.","A mid-branch match is only the current prefix. The success test waits for a node with no left child and no right child."],"takeaways":[{"title":"One number is enough state","body":"Only the running total decides the answer, so carrying it down each branch replaces storing every full path and cuts space from O(n*h) to O(h)."},{"title":"Match only at a leaf","body":"A total equal to targetSum counts only where both children are absent, otherwise an internal prefix would be accepted as a finished path."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"starterFunctionName":"hasPathSum","tags":["Tree","Depth-First Search","Recursion"]}
