Maximum Path Sum in Binary Tree in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to find the maximum path sum in a binary tree grows as the tree gets bigger.
Specifically, how does the number of steps change when the number of nodes increases?
Analyze the time complexity of the following code snippet.
function maxPathSum(root: TreeNode | null): number {
let maxSum = -Infinity;
function helper(node: TreeNode | null): number {
if (!node) return 0;
const left = Math.max(helper(node.left), 0);
const right = Math.max(helper(node.right), 0);
maxSum = Math.max(maxSum, node.val + left + right);
return node.val + Math.max(left, right);
}
helper(root);
return maxSum;
}
This code finds the maximum sum of values along any path in a binary tree, where a path can start and end at any node.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Each node is visited exactly one time during the recursion.
As the number of nodes grows, the function visits each node once, so the total steps grow roughly the same as the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The number of operations grows linearly with the number of nodes.
Time Complexity: O(n)
This means the time to find the maximum path sum grows directly in proportion to the number of nodes in the tree.
[X] Wrong: "The recursion visits nodes multiple times, so the time is more than linear."
[OK] Correct: Each node is visited once, and results are combined on the way back, so no repeated full visits happen.
Understanding this time complexity helps you explain how your solution scales and shows you can analyze recursive tree problems clearly.
"What if the tree was balanced vs very skewed? How would that affect the time complexity?"