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
트리를 쭉 순회하다가 리프노드에서 조건이 맞는지 검사하고 정답 리스트에 path를 추가해주면 된다. 매우 간단함.
참고로 recursive call 할 때 path를 복사하는 방법은 가독성은 좋으나 성능에 악영향이 심해서 스택처럼 push&pop하는게 submission 후 결과가 잘나온다.
# 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]]:
answer = []
def dfs(node, remaining):
remaining -= node.val
if not node.left and not node.right:
if remaining == 0:
answer.append(path[:])
return
if node.left:
path.append(node.left.val)
dfs(node.left, remaining)
path.pop()
if node.right:
path.append(node.right.val)
dfs(node.right, remaining)
path.pop()
if root:
path = [root.val]
dfs(root, targetSum)
return answer
시간복잡도는 최대 O(N^2)이다.
이렇게 skewed된 트리에서 모든 노드 값이 0이고 targetsum도 0이면 리프노드에 도달할때마다 2,3,4,5,..길이의 path를 정답리스트에 복사해 넣어야된다. 정답리스트를 제외하면 공간복잡도는 O(N)이 된다.
'코딩 테스트 및 알고리즘 > leetcode for google' 카테고리의 다른 글
leetcode : Longest Consecutive Sequence (1) | 2022.09.24 |
---|---|
leetcode : Concatenation of Consecutive Binary Numbers (0) | 2022.09.24 |
leetcode : Palindrome Partitioning (0) | 2022.09.22 |
leetcode : Maximum Score from Performing Multiplication Operations (0) | 2022.09.22 |
leetcode : Sum of Even Numbers After Queries (0) | 2022.09.21 |