Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 30fb11f

Browse files
Create path_sum.py
1 parent 418d585 commit 30fb11f

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

‎day-23/path_sum.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /