DP on Trees Maximum Path Sum in DSA C - Time & Space Complexity
We want to understand how the time needed to find the maximum path sum in a tree grows as the tree gets bigger.
How does the number of steps change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
int max(int a, int b) { return (a > b) ? a : b; }
int maxPathSumUtil(struct Node* root, int* res) {
if (root == NULL) return 0;
int left = max(0, maxPathSumUtil(root->left, res));
int right = max(0, maxPathSumUtil(root->right, res));
*res = max(*res, left + right + root->val);
return max(left, right) + root->val;
}
int maxPathSum(struct Node* root) {
int res = INT_MIN;
maxPathSumUtil(root, &res);
return res;
}
This code finds the maximum sum of values on any path in a binary tree by visiting each node once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Exactly once per node in the tree.
As the number of nodes grows, the function visits each node once, doing a fixed amount of work per node.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows directly with the number of nodes, so doubling nodes roughly doubles work.
Time Complexity: O(n)
This means the time to find the maximum path sum grows linearly with the number of nodes in the tree.
[X] Wrong: "The recursion might visit nodes multiple times, so it could be slower than linear."
[OK] Correct: Each node is visited once because the recursion only goes down each branch once, so no repeated work happens.
Understanding this linear time complexity helps you explain how efficient your tree algorithms are, a key skill in interviews.
"What if the tree was very unbalanced, like a linked list? How would the time complexity change?"