0
0
DSA Javascriptprogramming~5 mins

Maximum Path Sum in Binary Tree in DSA Javascript - 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.

Specifically, how does the number of steps change when the number of nodes increases?

Scenario Under Consideration

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

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

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

Pattern observation: The number of operations grows linearly with the number of nodes.

Final Time Complexity

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.

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 time complexity helps you explain how efficient your tree algorithms are, a key skill in many coding challenges and interviews.

Self-Check

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