Tech for good

[Leetcode/Tree, DFS, Binary Tree, Recursion] 112. Path Sum 본문

IT/Computer Science

[Leetcode/Tree, DFS, Binary Tree, Recursion] 112. Path Sum

Diana Kang 2025. 7. 23. 04:50

 

Binary Tree Binary Search Tree
 
  • Ascending
  • Left to Right
  •  
# 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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if root is None:
            return False

        if not root.left and not root.right:
            return targetSum == root.val
        
        right = self.hasPathSum(root.right, targetSum-root.val)
        left = self.hasPathSum(root.left, targetSum-root.val)

        return left or right