Path Sum

Easy#112top-down

You get the root of a binary tree and a target number. Say whether some path from the root down to a leaf, a node without children, adds up to the target. Our tree: 6 with children 4 and 3; 4 has only a right child 5, and 3 has children 1 and 2. Target 10 — the answer is true: 6 → 3 → 1. 6 → 4 also makes 10, but 4 is not a leaf.

input
root: a binary tree, written as on LeetCode: its values level by level, left to right, null for a missing child. targetSum: an integer.
returns
true if some path from the root down to a leaf (a node with no children) has values that add up to targetSum; otherwise false. An empty tree has no paths.
constraints
  • 0 ≤ the number of nodes ≤ 1000
  • −1000 ≤ Node.val ≤ 1000
  • −1000 ≤ targetSum ≤ 1000
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {boolean}
 */
function hasPathSum(root, targetSum) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.