leetcode_gym/_problems/pathSum.md
2026-08-25 19:14:07 -06:00

2.1 KiB

layout, title, last_solved, category, leetcode_url, status
layout title last_solved category leetcode_url status
page Path Sum tree https://leetcode.com/problems/path-sum Attempted

Problem

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Solution

Use dfs helper to pass down currentSum. Check if leaf node and sumTotal==targetSum.

{% highlight python %}

def hasPathSum(self, root: TreeNode, sum: int) -> bool:

    def dfs(node, currentSum, targetSum):

        if not node:
            return False
        
        # if current node is leaf and sum of all vals == targetSum
        if node.left is None and node.right is None and currentSum + node.val == targetSum:
            return True

        leftRes = dfs(node.left, currentSum + node.val, targetSum)
        rightRes = dfs(node.right, currentSum + node.val, targetSum)

        return leftRes or rightRes

    return dfs(root, 0, sum)

{% endhighlight %}


{% highlight python %}

def dfs(root, sum):

if not root:
    return False

# if the current node is a leaf and it's value is equal to the sum, we found a path
if root.val==sum and root.left is None and root.right is None:
    return True

# recursively call to traverse the left and right sub-tree
# return true if any of the two recursive call return true
leftRes = dfs(root.left, sum-root.val)
rightRes = dfs(root.right, sum-root.val)

return leftRes or rightRes

return dfs(root, sum)

{% endhighlight %}

image1