0
0
DSA Cprogramming~5 mins

DP on Trees Maximum Path Sum in DSA C - Time & Space Complexity

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

Scenario Under Consideration

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

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

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

Pattern observation: The work grows directly with the number of nodes, so doubling nodes roughly doubles work.

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

Interview Connect

Understanding this linear time complexity helps you explain how efficient your tree algorithms are, a key skill in interviews.

Self-Check

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