0
0
DSA Javascriptprogramming~5 mins

Diameter of Binary Tree in DSA Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Diameter of Binary Tree
O(n)
Understanding Time Complexity

We want to understand how the time needed to find the diameter of a binary tree changes as the tree grows.

Specifically, how does the number of steps grow when the tree has more nodes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function diameterOfBinaryTree(root) {
  let diameter = 0;
  function depth(node) {
    if (!node) return 0;
    const left = depth(node.left);
    const right = depth(node.right);
    diameter = Math.max(diameter, left + right);
    return 1 + Math.max(left, right);
  }
  depth(root);
  return diameter;
}
    

This code finds the longest path between any two nodes in a binary tree by calculating depths recursively.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Recursive calls to visit each node once.
  • How many times: Each node is visited exactly one time.
How Execution Grows With Input

As the number of nodes 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 grow in a straight line with the number of nodes.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the diameter grows directly with the number of nodes in the tree.

Common Mistake

[X] Wrong: "The function visits nodes multiple times, so it must be slower than linear."

[OK] Correct: Each node is visited only once during the depth calculation, so the total work is proportional to the number of nodes.

Interview Connect

Understanding this time complexity helps you explain how recursive tree algorithms scale, a common skill interviewers look for.

Self-Check

"What if we changed the code to calculate diameter by separately computing depths for each node without caching? How would the time complexity change?"