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.
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right)
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.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Once per node in the tree.
As the number of nodes grows, the function visits each node once to check paths.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls |
| 100 | About 100 calls |
| 1000 | About 1000 calls |
Pattern observation: The work grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to check paths 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 explores all root-to-leaf paths by visiting every node, so it must check many nodes, not just one path.
Understanding this helps you explain how recursive tree traversal scales, a common skill in interviews.
"What if the tree is balanced vs completely skewed? 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 target sum.Step 2: Differentiate from other tree properties
It is not about depth, counting leaves, or total sum, but specifically about a path sum from root to leaf.Final Answer:
If there exists a root-to-leaf path with a sum equal to a given target -> Option BQuick Check:
Path sum means root-to-leaf sum check [OK]
- Confusing path sum with total tree sum
- Checking sum for any path, not root-to-leaf
- Counting nodes instead of summing values
Solution
Step 1: Check parameter types and return type
The function should take a pointer to the root node (TreeNode*) and an integer target sum, and return a boolean indicating if such a path exists.Step 2: Validate each option
bool hasPathSum(TreeNode* root, int targetSum) uses pointer and bool return type, which is correct. Options B and D pass TreeNode by value (less efficient), and B returns int, C returns void which is incorrect.Final Answer:
bool hasPathSum(TreeNode* root, int targetSum) -> Option DQuick Check:
Pointer input and bool output needed [OK]
- Passing node by value instead of pointer
- Using wrong return type like void or int
- Missing pointer symbol (*) in parameter
#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) return root->val == targetSum;
return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
}
int main() {
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(4);
root->right = new TreeNode(8);
root->left->left = new TreeNode(11);
root->left->left->left = new TreeNode(7);
root->left->left->right = new TreeNode(2);
root->right->left = new TreeNode(13);
root->right->right = new TreeNode(4);
root->right->right->right = new TreeNode(1);
bool result = hasPathSum(root, 22);
std::cout << (result ? "true" : "false") << std::endl;
return 0;
}Solution
Step 1: Trace the path sums in the tree
Check if any root-to-leaf path sums to 22. One path is 5->4->11->2 = 22.Step 2: Confirm function logic and output
The function correctly returns true if such a path exists. The code prints "true".Final Answer:
true -> Option AQuick Check:
Path 5+4+11+2 = 22 found [OK]
- Ignoring leaf node condition
- Subtracting values incorrectly
- Assuming no path matches without checking all
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) return false;
if (root->left == nullptr && root->right == nullptr) return targetSum == root->val;
return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
}Solution
Step 1: Analyze recursive calls
The function calls itself with the same targetSum without subtracting the current node's value, so it never reduces the sum along the path.Step 2: Identify correct recursive logic
It should call hasPathSum(root->left, targetSum - root->val) and similarly for right to correctly track remaining sum.Final Answer:
The targetSum is not reduced by root->val in recursive calls -> Option CQuick Check:
Subtract node value each step [OK]
- Not updating targetSum in recursive calls
- Confusing base case return values
- Returning wrong data type
Solution
Step 1: Consider negative values in path sum
The standard recursive algorithm subtracts the current node's value (which can be negative) from the targetSum at each step, correctly handling negatives, zeros, and positives for root-to-leaf paths.Step 2: No change required
The problem is specifically for root-to-leaf paths, not arbitrary paths, so no modification is needed.Final Answer:
No modification needed; the standard path sum check works for all values -> Option AQuick Check:
Recursion handles negatives via subtraction [OK]
- Thinking negatives require checking all paths
- Using global variables unnecessarily
- Changing return type without reason
Ready to prove it?
Pass the test and this pattern moves unknown
