LeetCode solutions

112. Path Sum

My accepted Python solution to LeetCode problem 112, Path Sum, running in 0ms.

  • Difficulty: Easy
  • Python
  • Runtime 0ms
  • Memory 14.4MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 14.4MB, accepted 2025-12-23.

python
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def hasPathSum(self, root, targetSum):
        if not root:
            return False
        # If leaf node, check if current value equals remaining sum
        if not root.left and not root.right:
            return root.val == targetSum
        # Recursively check left and right subtrees
        return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)

Source