LeetCode - 112. Path Sum (Python)

조민수·2024년 6월 4일
0

LeetCode

목록 보기
11/61

Easy, DFS

RunTime : 35 ms / Memory : 17.37 MB


문제

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.


풀이

  • 루트부터 리프노드까지 DFS하며 값을 갱신하는 문제
  • LeetCode는 아에 Node를 Class로 만들어 파라미터로 넘겨준다.
    • 맨날 인접 행렬 or 그래프로만 풀다가 이렇게 접하니까 신선한데 어려움
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        
        if not root.left and not root.right:    # leaf
            return targetSum == root.val
        
        leftSum = self.hasPathSum(root.left, targetSum - root.val)
        rightSum = self.hasPathSum(root.right, targetSum - root.val)
        
        return leftSum or rightSum
profile
사람을 좋아하는 Front-End 개발자

0개의 댓글