one line of code at a time

[leetcode] 112. Path Sum 파이썬 코드 본문

leetcode

[leetcode] 112. Path Sum 파이썬 코드

oloc 2024. 8. 17. 03:31

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

 

루트노드부터 단말노드까지 노드의 val 값을 더했을 때 targetSum과 같아지는 path가 있으면 true, 없으면 false를 반환하는 문제이다.

 

class Solution(object):
    def hasPathSum(self, root, targetSum):
        
        def dfs(root, curr_sum):
            if not root:
                return False

            curr_sum += root.val
            if not root.left and not root.right:
                return curr_sum == targetSum
            return dfs(root.left, curr_sum) or dfs(root.right, curr_sum)
            
        return dfs(root, 0)