Path Sum Root to Leaf in Binary Tree in DSA Typescript - Time & Space Complexity
We want to know how long it takes to check if a path from the root to any leaf adds up to a target sum in a binary tree.
How does the time needed grow as the tree gets bigger?
Analyze the time complexity of the following code snippet.
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
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);
}
This code checks if there is any 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 checks each node once to find paths.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 node visits |
| 100 | About 100 node visits |
| 1000 | About 1000 node visits |
Pattern observation: The operations grow roughly in direct proportion to the number of nodes.
Time Complexity: O(n)
This means the time needed 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 possible paths to leaves, so it must visit every node in the worst case.
Understanding this helps you explain how recursive tree traversal works and how to analyze its cost, a common skill in interviews.
"What if the tree was a linked list (each node has only one child)? How would the time complexity change?"