MediumNo. 0113

Path Sum II — LeetCode 113 Python Solution

Topics
Tree, Depth-First Search, Backtracking, Binary Tree
Reading time
4 min

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

PythonSolution
# 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 ans

Complexity

Time
O(n2)where n is the number of nodes in the binary tree
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0112Path SumEasy
0257Binary Tree PathsEasy
0988Smallest String Starting From LeafMedium
0079Word SearchMedium
0797All Paths From Source to TargetMedium
0039Combination SumMedium

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(n2), 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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.