Path Sum Root to Leaf in Binary Tree in DSA Python - Time & Space Complexity
We want to understand how the time needed to check if a path sum exists in a binary tree grows as the tree gets bigger.
Specifically, how does the number of steps change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
def hasPathSum(root, targetSum):
if not root:
return False
if not root.left and not root.right:
return root.val == targetSum
return (hasPathSum(root.left, targetSum - root.val) or
hasPathSum(root.right, targetSum - root.val))
This code checks if there is a root-to-leaf path in a binary tree where the sum of node values equals the target sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Each node is visited once in the worst case.
As the number of nodes (n) in the tree grows, the function visits each node once to check paths.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The number of steps grows roughly in direct proportion to the number of nodes.
Time Complexity: O(n)
This means the time to check the path sum grows linearly with the number of nodes in the tree.
[X] Wrong: "The function only checks one path, so it runs in constant time."
[OK] Correct: The function must explore all possible root-to-leaf paths, so it visits every node in the tree in the worst case.
Understanding this linear time complexity helps you explain how recursive tree traversal works and why it is efficient for path sum problems.
"What if the tree was a linked list (all nodes have only one child)? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem statement
The problem asks if there is any path from the root node down to any leaf node where the sum of the node values equals a given target sum.Step 2: Identify what is being checked
We check paths that start at the root and end at leaves, summing node values along the way, to see if any path matches the target sum.Final Answer:
If such a path exists, return true; otherwise, false -> Option AQuick Check:
Path sum check = existence of root-to-leaf path with target sum [OK]
- Checking sum for any path, not just root-to-leaf
- Confusing leaf nodes with internal nodes
- Summing all nodes instead of a single path
Solution
Step 1: Identify correct parameter order and types
The function should take the root node first, then the target sum, matching the problem context.Step 2: Confirm return type is boolean
The function returns True or False depending on whether the path exists, so return type is bool.Final Answer:
def has_path_sum(root: TreeNode, target_sum: int) -> bool: -> Option DQuick Check:
Correct signature = root, target_sum, returns bool [OK]
- Swapping parameter order
- Wrong return type annotation
- Missing type hints or incorrect ones
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):
if not root:
return False
if not root.left and not root.right:
return root.val == target_sum
return has_path_sum(root.left, target_sum - root.val) or has_path_sum(root.right, target_sum - root.val)
root = TreeNode(5, TreeNode(4, TreeNode(11, TreeNode(7), TreeNode(2))), TreeNode(8, TreeNode(13), TreeNode(4, None, TreeNode(1))))
print(has_path_sum(root, 22))Solution
Step 1: Trace the root-to-leaf paths and their sums
Paths: 5->4->11->7 = 27, 5->4->11->2 = 22, 5->8->13 = 26, 5->8->4->1 = 18.Step 2: Check if any path sum equals 22
The path 5->4->11->2 sums to 22, so function returns True.Final Answer:
True -> Option AQuick Check:
Path sum 22 exists = True [OK]
- Not subtracting node values from target_sum
- Ignoring leaf node condition
- Returning None instead of boolean
def has_path_sum(root, target_sum):
if root is None:
return False
if root.left is None and root.right is None:
return root.val == target_sum
return has_path_sum(root.left, target_sum) or has_path_sum(root.right, target_sum)Solution
Step 1: Analyze recursive calls and target_sum usage
The function calls itself with the same target_sum, not subtracting root.val, so sums are not updated correctly.Step 2: Identify correct recursive call adjustment
Each recursive call should reduce target_sum by root.val to track remaining sum needed.Final Answer:
target_sum not reduced by root.val in recursion -> Option CQuick Check:
Subtract node value from target_sum each step [OK]
- Forgetting to update target_sum in recursion
- Returning wrong base case values
- Confusing leaf node condition
Solution
Step 1: Evaluate the standard subtraction approach with negatives
The standard recursive method subtracts root.val from target_sum in recursive calls. This works correctly even with negative values because target_sum - root.val adjusts the remaining sum appropriately regardless of the sign.Step 2: Confirm no changes needed
No modification is necessary; the algorithm handles negative, zero, and positive values correctly without issues.Final Answer:
No modification needed; the standard approach works for all values -> Option BQuick Check:
Standard subtraction handles negatives [OK]
- Believing subtraction fails with negatives
- Using BFS unnecessarily for path sum
- Incorrectly pruning paths based on signs
Ready to prove it?
Pass the test and this pattern moves unknown
