|
| 1 | +# Problem: Path Sum |
| 2 | +# Link: https://leetcode.com/problems/path-sum/ |
| 3 | +# Tags: Tree, DFS, Recursion, Binary Tree |
| 4 | +# Approach: The solution applies a recursive DFS traversal. |
| 5 | +# At each step, the current node’s value is subtracted from the target sum. |
| 6 | +# If a leaf node is reached, the algorithm checks whether the remaining sum equals the leaf’s value. |
| 7 | +# If so, a valid path exists and the function returns True. |
| 8 | +# Otherwise, the recursion continues down the left and right subtrees, and the result is True if any root-to-leaf path satisfies the condition. |
| 9 | +# Time Complexity: O(n) – visit each node once |
| 10 | +# Space Complexity: O(h) – recursion stack, where h is the tree height |
| 11 | + |
| 12 | + |
| 13 | +class Solution: |
| 14 | + def hasPathSum(self, root, targetSum): |
| 15 | + if not root: |
| 16 | + return False |
| 17 | + |
| 18 | + # leaf check |
| 19 | + if not root.left and not root.right: |
| 20 | + return targetSum == root.val |
| 21 | + |
| 22 | + # DFS on children with reduced target |
| 23 | + return (self.hasPathSum(root.left, targetSum - root.val) or |
| 24 | + self.hasPathSum(root.right, targetSum - root.val)) |
0 commit comments