Path sum

Does some root-to-leaf path add up to a target value?

Time O(n)Space O(h)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Subtract the current node's value from the target as the search goes down, so by the time a leaf is reached, the question is simply whether the remaining target equals that leaf's value. Try the left subtree with the reduced target, then the right subtree, and the answer is true the moment either one succeeds.

Code

public static bool HasPathSum(TreeNode node, int target) {
    if (node == null) return false;
    if (node.left == null && node.right == null) return target == node.val;
    int remaining = target - node.val;
    return HasPathSum(node.left, remaining) || HasPathSum(node.right, remaining);
}
static boolean hasPathSum(TreeNode node, int target) {
    if (node == null) return false;
    if (node.left == null && node.right == null) return target == node.val;
    int remaining = target - node.val;
    return hasPathSum(node.left, remaining) || hasPathSum(node.right, remaining);
}
bool hasPathSum(TreeNode* node, int target) {
    if (!node) return false;
    if (!node->left && !node->right) return target == node->val;
    int remaining = target - node->val;
    return hasPathSum(node->left, remaining) || hasPathSum(node->right, remaining);
}
def has_path_sum(node: TreeNode | None, target: int) -> bool:
    if node is None: return False
    if node.left is None and node.right is None: return target == node.val
    remaining = target - node.val
    return has_path_sum(node.left, remaining) or has_path_sum(node.right, remaining)

Tips

In the .NET library

This "carry a running total down the recursion" idea generalises directly to listing every qualifying path, not just testing whether one exists, by appending to a list instead of returning a bool.