Path Sum Root to Leaf in Binary Tree in DSA C# - Time & Space Complexity
We want to know how the time needed to check if a path sum exists grows as the tree gets bigger.
How does the number of nodes affect the work done?
Analyze the time complexity of the following code snippet.
public bool HasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) {
return targetSum == root.val;
}
return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val);
}
This code checks if there is a root-to-leaf path 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 grows, the function visits each node once, so work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows linearly as the tree size increases.
Time Complexity: O(n)
This means the time to check the path sum grows in direct proportion to 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 explores all possible root-to-leaf paths, so it must visit every node to be sure.
Understanding this helps you explain how recursive tree traversal works and why visiting all nodes is necessary to solve path sum problems.
"What if the tree was balanced versus very skewed? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem statement
The problem asks to check if any path from the root node down to any leaf node sums up exactly to a given target value.Step 2: Identify what is being checked
We are not asked for maximum depth, total nodes, or sum of all nodes, but specifically for a path sum equal to the target.Final Answer:
If there exists a root-to-leaf path with a sum equal to a given target -> Option CQuick Check:
Path sum check = If there exists a root-to-leaf path with a sum equal to a given target [OK]
- Confusing path sum with total tree sum
- Checking any path, not just root-to-leaf
- Looking for maximum depth instead
Solution
Step 1: Determine the return type for path sum check
The function should return true or false indicating if such a path exists, so return type must be bool.Step 2: Check method signature correctness
public bool HasPathSum(TreeNode root, int targetSum) returns bool and takes root node and target sum as parameters, matching the problem requirements.Final Answer:
public bool HasPathSum(TreeNode root, int targetSum) -> Option AQuick Check:
Return type bool for yes/no check = public bool HasPathSum(TreeNode root, int targetSum) [OK]
- Using int or void return type instead of bool
- Returning string instead of boolean
- Incorrect parameter types or order
HasPathSum(root, 22) return?5 / \ 4 8 / / \ 11 13 4 / \ 7 2 1
Solution
Step 1: Identify root-to-leaf paths and their sums
Check 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
Path 5->4->11->2 sums to 22, so the method returns true.Final Answer:
true -> Option BQuick Check:
Path sum 22 exists = true [OK]
- Ignoring leaf node condition
- Summing partial paths not ending at leaf
- Miscomputing sums of nodes
public bool HasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) return root.val == targetSum;
return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val);
}Solution
Step 1: Analyze base cases and recursion
Code returns false if root is null, correctly handles leaf node by comparing value to targetSum, and recursively checks left and right subtrees with updated targetSum.Step 2: Confirm correctness of logic
All conditions and recursive calls are correct and return statements are present.Final Answer:
No bug; code works correctly -> Option AQuick Check:
Code logic matches problem requirements = No bug; code works correctly [OK]
- Forgetting to subtract node value from targetSum
- Missing return keyword in recursion
- Incorrect leaf node condition
Solution
Step 1: Understand the requirement to collect all paths
We need to find all root-to-leaf paths with sum equal to target, so we must track the current path during traversal.Step 2: Choose the correct traversal and tracking method
DFS with a list to store nodes along the current path allows backtracking and collecting all valid paths when leaf and sum conditions are met.Final Answer:
Use DFS with a list to track current path and add to result when sum matches at leaf -> Option DQuick Check:
Track paths with DFS and list = Use DFS with a list to track current path and add to result when sum matches at leaf [OK]
- Using BFS which is less natural for path tracking
- Not tracking path nodes, only sums
- Stopping at first found path instead of all
Ready to prove it?
Pass the test and this pattern moves unknown
