Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum 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  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

Solutions

1. DFS-递归

  思路是一样的,

# Time Complexity: O(n)
# Sapce Complexity: O(1)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        if not root:
            return []
        res = []
        self.dfs(root, sum, [], res)
        return res
    
    def dfs(self, root, sum, path, res):
        if not root.left and not root.right and sum == root.val:
            path.append(root.val)
            res.append(path)
        cur_sum = sum - root.val
        if root.left:
            self.dfs(root.left, cur_sum, path + [root.val], res)
        if root.right:
            self.dfs(root.right, cur_sum, path + [root.val], res)
# Runtime: 44 ms, faster than 99.04% of Python3 online submissions for Path Sum II.
# Memory Usage: 19.1 MB, less than 6.90% of Python3 online submissions for Path Sum II.

2. 迭代

# Time Complexity: O(n)
# Sapce Complexity: O(1)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        if not root:
            return []
        if not root.left and not root.right and sum == root.val:
            return [[root.val]]
        cur_sum = sum - root.val
        tmp = self.pathSum(root.left, cur_sum) + self.pathSum(root.right, cur_sum)
        
        return [[root.val] + path for path in tmp]
# Runtime: 56 ms, faster than 61.99% of Python3 online submissions for Path Sum II.
# Memory Usage: 15.6 MB, less than 37.93% of Python3 online submissions for Path Sum II.

References

  1. 113. Path Sum II
  2. Python solutions (Recursively, BFS+queue, DFS+stack)