파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 9. 24. 23:45

https://leetcode.com/problems/path-sum-ii/

 

Path Sum II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

DFS 를 이용해서 푸는 문제.
뭐든 트리는 Base condition 에 대해 생각하는게 중요한 듯.

class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        res = []
        def dfs(root, path, ans, rem_sum):
            if not root:
                return []

            path.append(root.val)

            if not root.left and not root.right and rem_sum == root.val:
                res.append(list(path))

            dfs(root.left, path, res, rem_sum - root.val)
            dfs(root.right, path, res, rem_sum - root.val)
            path.pop()
        
        dfs(root, [], res, targetSum)
        return res
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.09.27
Today's Challenge  (0) 2022.09.25
Today's Challenge  (0) 2022.09.23
Today's Challenge  (0) 2022.09.22
Today's Challenge  (0) 2022.09.21
Comments