Home Path Sum
Post
Cancel

Path Sum

Leetcode Problem

Path Sum

binary tree가 주어졌을 때, leaf node까지의 합과 targetSum이 일치하는 경우가 있는지를 판별하는 문제입니다.

1
2
3
4
5
6
7
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        if not root.left and not root.right:
            return targetSum - root.val == 0
        return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)

고민할 시간이 많지 않아 해답을 찾아봤습니다.
if not root.left and not root.right 조건까지는 생각해냈지만, targetSum에서 root.val을 뺀 값을 매개변수로 넣을 생각을 하지 못했습니다.





참고

This post is licensed under CC BY 4.0 by the author.