Description

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.

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

Example 1:

  • 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:
    5 + 4 + 11 + 2 = 22
    5 + 8 + 4 + 5 = 22

Example 2:

  • Input: root = [1,2,3], targetSum = 5
  • Output: []

Example 3:

  • Input: root = [1,2], targetSum = 0
  • Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

Submitted Code

# 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]]:
        if not root:
            return []
        
        result = []
        stack = [(root, root.val, [root.val])]

        while stack:
            node, currSum, path = stack.pop()

            if (not node.left and not node.right) and currSum == targetSum:
                result.append(path)

            if node.right:
                stack.append(
                    (node.right, currSum + node.right.val, path + [node.right.val])
                )

            if node.left:
                stack.append(
                    (node.left, currSum + node.left.val, path + [node.left.val])
                )

        return result

Runtime: 0 ms | Beats 100.00%
Memory: 20.09 MB | Beats 89.75%

112. Path Sum에서 한 단게 진화해서 targetSum을 만족하는 모든 경로를 반환해야 한다. 스택에 각 노드를 추가할 때마다 현재까지의 경로도 같이 저장하는 방법으로 간단하게 풀었다.

Other Solutions

1st

class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        res = []
        def dfs(node, path, curSum):
            if not node: return
            curSum += node.val
            path.append(node.val)
            if not node.left and not node.right and curSum == targetSum:
                res.append(path[:])
            dfs(node.left, path, curSum)
            dfs(node.right, path, curSum)
            path.pop()
        dfs(root, [], 0)
        return res

time complexity: 𝑂(𝑛)
space complexity: 𝑂(ℎ)

하나의 리스트만 path로 사용하고 백트래킹 기법으로 푸는 방법도 있다.

Leave a comment