코딩 알고리즘 문제/Leetcode

113. Path Sum II (Backtracking, Tree, Depth-First Search, Binary Tree)

highlightmoon 2025. 10. 27. 07:16
반응형

링크 - https://leetcode.com/problems/path-sum-ii/description/?envType=company&envId=tiktok&favoriteSlug=tiktok-thirty-days

난이도 - Medium

Intuition

우리는 Binary Search Tree를 통해 이 문제를 풀 수 있다. 중요한점은 cur_path로 매 노드마다 현재 path를 list로 넘길 때, 현재 노드의 값을 append해주고 탐색이 끝나면 cur_path에서 pop을 해줘야 다른 노드 탐색에 영향이 없다.

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]]:
        ans = []

        if not root:
            return ans

        def bst(node, cur_sum, cur_path):
            cur_sum += node.val
            cur_path.append(node.val)
            if not node.left and not node.right:
                if cur_sum == targetSum:
                    ans.append(cur_path[:])

            if node.left:
                bst(node.left, cur_sum, cur_path)
            if node.right:
                bst(node.right, cur_sum, cur_path)
            cur_path.pop()

        bst(root, 0, [])
        return ans

Complexity

Time Complexity: O(N^2)

Space Complexity: O(N)

반응형