Maximum Path Sum in Binary Tree in DSA Javascript - 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) {
let maxSum = -Infinity;
function dfs(node) {
if (!node) return 0;
const left = Math.max(dfs(node.left), 0);
const right = Math.max(dfs(node.right), 0);
maxSum = Math.max(maxSum, node.val + left + right);
return node.val + Math.max(left, right);
}
dfs(root);
return maxSum;
}
This code finds the maximum sum of any path in a binary tree, where a path can start and end at any nodes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive depth-first search (dfs) visits each node once.
- How many times: Each node is visited exactly one time during recursion.
As the number of nodes grows, the function visits each node once, so the total steps grow roughly in direct proportion to 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 in a straight line with 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 work happens.
Understanding this time complexity helps you explain how efficient your tree algorithms are, a key skill in many coding challenges and interviews.
"What if the tree was very unbalanced, like a linked list? How would the time complexity change?"