Skip to contentKEEP THE CRAFTTHE SANCTUARY

Path Sum II

List every root-to-leaf path whose values add up to a target.

The problem

Implement Solution.pathSum(root, targetSum). root is the root TreeNode of a binary tree, or None for an empty tree; each node has val, left and right. Return every path that starts at the root, ends at a leaf (a node with no children), and whose values add up to targetSum. Write each path as the list of its values from the root down. Return the paths in left-to-right order, the order a depth-first search that visits left before right finds their leaves. Return [] when no path matches. Trees are written in level order with None for a missing child. For [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1] and targetSum = 22, return [[5, 4, 11, 2], [5, 8, 4, 5]]. A path that reaches the target at a node with children does not count. Constraints: the tree has 0 to 5,000 nodes; node values and targetSum are integers from -1,000 to 1,000, so sums can go down as well as up. Do not change the tree.

Starter code

class Solution:
    def pathSum(self, root, targetSum):
        pass

Public examples

  1. root = [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1], targetSum = 22gives[[5, 4, 11, 2], [5, 8, 4, 5]]
  2. root = [-3], targetSum = -3gives[[-3]]
  3. root = [0], targetSum = 0gives[[0]]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.