🎯 Problem: Insufficient Nodes in Root to Leaf Paths
📖 The Real Problem
You are given a binary tree and a target sum. Your task is to determine if the tree has any root-to-leaf path where the sum of all node values along the path equals the target sum.
Why this problem exists:
- Many tree algorithms require understanding path traversal
- This is a fundamental problem that tests understanding of recursion and tree traversal
- It's a building block for more complex tree path problems
💡 Why This Matters
Real-world applications:
- Decision trees in machine learning use similar path evaluation
- Network routing algorithms evaluate paths with cost constraints
- Game trees in AI evaluate move sequences with score targets
- File system navigation with size/depth constraints
Skills you'll develop:
- ✅ Recursive tree traversal
- ✅ Path sum calculation
- ✅ Base case identification in trees
- ✅ Backtracking concepts
📋 Contributor Tasks
Step 1: Understand the Problem
- Read the problem statement carefully
- Draw a simple binary tree on paper
- Trace a few root-to-leaf paths manually
- Calculate path sums for each path
Step 2: Plan Your Approach
- Decide on traversal method (DFS recommended)
- Identify base cases:
- Empty node (null)
- Leaf node (no children)
- Plan recursive strategy:
- Subtract current node value from target sum
- Recurse on left and right subtrees
Step 3: Implement the Solution
- Create a function that takes (node, target_sum)
- Handle the null node case
- Handle the leaf node case
- Recurse on children with updated target sum
- Return True if either subtree has a valid path
Step 4: Test Your Solution
- Test with empty tree
- Test with single node tree
- Test with tree where path exists
- Test with tree where no path exists
- Test with negative values
✅ Expected Outcome
Your solution should:
Function Signature:
def hasPathSum(root, targetSum):
"""
Determine if tree has root-to-leaf path with target sum.
Args:
root: TreeNode - root of binary tree
targetSum: int - target sum to find
Returns:
bool: True if path exists, False otherwise
"""
Expected Behavior:
- ✅ Returns True if ANY root-to-leaf path sums to target
- ✅ Returns False if NO path matches target
- ✅ Handles empty tree (returns False)
- ✅ Handles single node tree correctly
- ✅ Works with negative values in nodes
Example Test Cases:
# Test 1: Path exists
# Tree: 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ \
# 7 2 1
hasPathSum(root, 22) # Returns: True (5→4→11→2 = 22)
# Test 2: No path exists
# Tree: 1
# / \
# 2 3
hasPathSum(root, 5) # Returns: False
# Test 3: Empty tree
hasPathSum(None, 0) # Returns: False
# Test 4: Single node
# Tree: 5
hasPathSum(root, 5) # Returns: True
hasPathSum(root, 3) # Returns: False
📚 Additional Context & References
Tree Node Structure
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
Key Concepts to Understand
1. Root-to-Leaf Path:
- Must start at root
- Must end at a leaf node (node with no children)
- Cannot stop at intermediate nodes
2. DFS Traversal:
# Typical DFS pattern for trees
def dfs(node):
if not node:
return
# Process current node
dfs(node.left)
dfs(node.right)
3. Base Cases:
- Null node: Return False (no path)
- Leaf node: Check if remaining sum equals node value
Hints (Use Only If Stuck!)
💡 Hint 1
Think about what happens when you reach a leaf node. What should you check?
💡 Hint 2
At each node, you can subtract its value from the target sum and pass the remaining sum to children.
💡 Hint 3
A leaf node is a node where both left and right children are None.
Complexity Analysis
Time Complexity: O(n)
- Visit each node once in worst case
- n = number of nodes in tree
Space Complexity: O(h)
- Recursion stack depth
- h = height of tree
- Worst case: O(n) for skewed tree
- Best case: O(log n) for balanced tree
Related Problems
Once you solve this, try these related problems:
- Path Sum II - Find ALL paths that sum to target
- Binary Tree Maximum Path Sum - Find maximum path sum (any path)
- Sum Root to Leaf Numbers - Treat paths as numbers
Helpful Resources
📝 Notes
- A leaf node is defined as a node with NO children
- Empty tree (root = None) should return False
- Node values can be negative
- Target sum can be negative
- Path must go from root ALL THE WAY to a leaf
Ready to contribute?
- Fork the repository
- Create your solution file
- Test thoroughly
- Submit a pull request!
File Location: exercises/1000_programs/medium/1080_insufficient_nodes_path_sum.py
🚀 Happy coding!
🎯 Problem: Insufficient Nodes in Root to Leaf Paths
📖 The Real Problem
You are given a binary tree and a target sum. Your task is to determine if the tree has any root-to-leaf path where the sum of all node values along the path equals the target sum.
Why this problem exists:
💡 Why This Matters
Real-world applications:
Skills you'll develop:
📋 Contributor Tasks
Step 1: Understand the Problem
Step 2: Plan Your Approach
Step 3: Implement the Solution
Step 4: Test Your Solution
✅ Expected Outcome
Your solution should:
Function Signature:
Expected Behavior:
Example Test Cases:
📚 Additional Context & References
Tree Node Structure
Key Concepts to Understand
1. Root-to-Leaf Path:
2. DFS Traversal:
3. Base Cases:
Hints (Use Only If Stuck!)
💡 Hint 1
Think about what happens when you reach a leaf node. What should you check?💡 Hint 2
At each node, you can subtract its value from the target sum and pass the remaining sum to children.💡 Hint 3
A leaf node is a node where both left and right children are None.Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(h)
Related Problems
Once you solve this, try these related problems:
Helpful Resources
📝 Notes
Ready to contribute?
File Location:
exercises/1000_programs/medium/1080_insufficient_nodes_path_sum.py🚀 Happy coding!