Skip to content

Files

Latest commit

Zanger67/leetcodeZanger67/leetcode
Zanger67/leetcode
and
Zanger67/leetcode
Jan 20, 2025
8d4889c · Jan 20, 2025

History

History
52 lines (39 loc) · 1.44 KB

_112. Path Sum.md

File metadata and controls

52 lines (39 loc) · 1.44 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 03, 2024

Last updated : July 03, 2024


Related Topics : Tree, Depth-First Search, Breadth-First Search, Binary Tree

Acceptance Rate : 52.09 %


Solutions

Python

# 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 not root :
            return False

        def dfs(curr: Optional[TreeNode], remaining: int) -> bool :
            if not curr :
                return remaining == 0
        
            remaining -= curr.val
            if curr.left and curr.right :
                return dfs(curr.left, remaining) or \
                       dfs(curr.right, remaining)
            if curr.left :
                return dfs(curr.left, remaining)
            return dfs(curr.right, remaining)
        
        return dfs(root, targetSum)