Maximum Path Sum in Binary Tree in DSA C++ - 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.
The question is: how does the number of steps change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
int maxPathSumHelper(TreeNode* node, int& maxSum) {
if (!node) return 0;
int left = max(0, maxPathSumHelper(node->left, maxSum));
int right = max(0, maxPathSumHelper(node->right, maxSum));
maxSum = max(maxSum, left + right + node->val);
return max(left, right) + node->val;
}
int maxPathSum(TreeNode* root) {
int maxSum = INT_MIN;
maxPathSumHelper(root, maxSum);
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 nodes.
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.
As the number of nodes in the tree increases, the function visits each node once, so the total steps grow directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The steps increase in a straight line as the tree grows.
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 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 linear time complexity helps you explain efficient tree traversal and recursion skills clearly in interviews.
"What if the tree was very unbalanced and looked like a linked list? How would the time complexity change?"