gary@interview:~/interview/coding/113-path-sum-ii.md$
$ cat ./coding/113-path-sum-ii.md
[Coding]

113. Path Sum II

────────────────────────────────────────────────────────────

113. Path Sum II

這一題比較困難的是,雖然是樹的遍歷加上回溯法。

# 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: TreeNode, targetSum: int) -> List[List[int]]:

        result = []
        def backtrack(node, targetSum, curr):
            if not node:
                return 

            curr.append(node.val)
            if node.val == targetSum and not node.left and not node.right:
                result.append(list(curr))
            else:
                backtrack(node.left, targetSum - node.val, curr)
                backtrack(node.right, targetSum - node.val, curr)
            curr.pop()

        backtrack(root, targetSum, [])
        return result

--tags#Tree
$ ls ./coding/ | grep -v 113-path-sum-ii
265. Paint House II256. Paint House143. Reorder List1762. Buildings With an Ocean View
← cd ../codingcd ~