0
0
DSA C++programming~5 mins

Maximum Path Sum in Binary Tree in DSA C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Maximum Path Sum in Binary Tree
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10About 10 visits
100About 100 visits
1000About 1000 visits

Pattern observation: The steps increase in a straight line as the tree grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the maximum path sum grows linearly with the number of nodes in the tree.

Common Mistake

[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.

Interview Connect

Understanding this linear time complexity helps you explain efficient tree traversal and recursion skills clearly in interviews.

Self-Check

"What if the tree was very unbalanced and looked like a linked list? How would the time complexity change?"