Path Sum II — LeetCode 113 Python Solution
- Problem
- #113
- Pattern
- Backtracking
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.
Example
- Input
- root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
- Output
- [[5,4,11,2],[5,8,4,5]]
- Explanation
- There are two paths whose sum equals targetSum:
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) -> List[List[int]]:
def dfs(root, s):
if root is None:
return
s += root.val
t.append(root.val)
if root.left is None and root.right is None and s == targetSum:
ans.append(t[:])
dfs(root.left, s)
dfs(root.right, s)
t.pop()
ans = []
t = []
dfs(root, 0)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the number of nodes in the binary tree |
| Space | O(n) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 113. Path Sum II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 113. Path Sum II?
- LeetCode 113. Path Sum II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 113. Path Sum II?
- The Python solution on this page runs in O(n^2), where n is the number of nodes in the binary tree.
- What is the space complexity of LeetCode 113. Path Sum II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 113. Path Sum II cover?
- LeetCode 113. Path Sum II is tagged Tree, Depth-First Search, Backtracking and Binary Tree on LeetCode.