Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Path Sum in Python
The Path Sum problem asks us to determine if there exists a root-to-leaf path in a binary tree where the sum of node values equals a given target sum. This is a classic tree traversal problem that can be solved using recursion.
Algorithm
The solution uses a recursive approach with these steps ?
If the root is null, return False (no path exists)
If we reach a leaf node, check if the remaining sum equals the leaf's value
Otherwise, recursively check left and right subtrees with the reduced sum
Implementation
# 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
def has_path_sum(root, target_sum):
"""
Check if there exists a root-to-leaf path with given sum
"""
if not root:
return False
# If it's a leaf node, check if sum matches
if not root.left and not root.right:
return target_sum == root.val
# Recursively check left and right subtrees
remaining_sum = target_sum - root.val
return (has_path_sum(root.left, remaining_sum) or
has_path_sum(root.right, remaining_sum))
# Create the example tree: [0, -3, 9, -10, None, 5]
root = TreeNode(0)
root.left = TreeNode(-3)
root.right = TreeNode(9)
root.left.left = TreeNode(-10)
root.right.right = TreeNode(5)
# Test with target sum of 14
result = has_path_sum(root, 14)
print(f"Path with sum 14 exists: {result}")
# Test with target sum of -13 (0 ? -3 ? -10)
result2 = has_path_sum(root, -13)
print(f"Path with sum -13 exists: {result2}")
Path with sum 14 exists: True Path with sum -13 exists: True
How It Works
The algorithm explores all possible root-to-leaf paths by reducing the target sum at each node ?
Start with the root and target sum (14)
Subtract current node value from sum: 14 - 0 = 14
Explore right subtree with remaining sum 14
At node 9: 14 - 9 = 5
At leaf node 5: 5 == 5 ? (path found)
Alternative Implementation with Path Tracking
def find_path_sum_with_path(root, target_sum, current_path=[]):
"""
Find path and return both result and the actual path
"""
if not root:
return False, []
current_path = current_path + [root.val]
# If leaf node, check sum
if not root.left and not root.right:
if sum(current_path) == target_sum:
return True, current_path
return False, []
# Check left subtree
found, path = find_path_sum_with_path(root.left, target_sum, current_path)
if found:
return True, path
# Check right subtree
found, path = find_path_sum_with_path(root.right, target_sum, current_path)
return found, path
# Test with the same tree
found, path = find_path_sum_with_path(root, 14)
print(f"Path found: {found}")
print(f"Actual path: {' ? '.join(map(str, path))}")
print(f"Sum: {sum(path)}")
Path found: True Actual path: 0 ? 9 ? 5 Sum: 14
Time and Space Complexity
| Complexity | Value | Explanation |
|---|---|---|
| Time | O(n) | Visit each node once in worst case |
| Space | O(h) | Recursion stack depth equals tree height |
Conclusion
The Path Sum problem is efficiently solved using recursive depth-first search. The key insight is to reduce the target sum at each level until reaching a leaf node where we can verify if the path sum matches the target.
