Skip to content

Commit 59110f5

Browse files
committed
Added solution for binary tree path sum problem #1080
1 parent fed9345 commit 59110f5

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def hasPathSum(root, targetSum):
2+
"""
3+
Determine if tree has root-to-leaf path with target sum.
4+
This logic is fundamental for Decision Trees in Machine Learning.
5+
"""
6+
# Base Case: Agar tree khali hai
7+
if not root:
8+
return False
9+
10+
# Check if we are at a leaf node (node with no children)
11+
if not root.left and not root.right:
12+
# Check if the remaining sum matches the current node's value
13+
return root.val == targetSum
14+
15+
# Recursive step: Subtract current node's value from targetSum
16+
# and search in children subtrees
17+
remaining_sum = targetSum - root.val
18+
19+
return hasPathSum(root.left, remaining_sum) or hasPathSum(root.right, remaining_sum)

0 commit comments

Comments
 (0)