Path Sum III — LeetCode 437 Python Solution
- Problem
- #437
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Example
- Input
- root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
- Output
- 3
- Explanation
- The paths that sum to 8 are shown.
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
def dfs(node, s):
if node is None:
return 0
s += node.val
ans = cnt[s - targetSum]
cnt[s] += 1
ans += dfs(node.left, s)
ans += dfs(node.right, s)
cnt[s] -= 1
return ans
cnt = Counter({0: 1})
return dfs(root, 0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of nodes in the binary tree auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 437. Path Sum III is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 437. Path Sum III?
- LeetCode 437. Path Sum III is rated Medium on LeetCode.
- What is the time complexity of LeetCode 437. Path Sum III?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 437. Path Sum III?
- The Python solution on this page uses O(n), where n is the number of nodes in the binary tree auxiliary space.
- What topics does LeetCode 437. Path Sum III cover?
- LeetCode 437. Path Sum III is tagged Tree, Depth-First Search and Binary Tree on LeetCode.