Diameter of Binary Tree in DSA Typescript - Time & Space Complexity
We want to understand how long it takes to find the diameter of a binary tree.
The question is: how does the time grow as the tree gets bigger?
Analyze the time complexity of the following code snippet.
function diameterOfBinaryTree(root: TreeNode | null): number {
let diameter = 0;
function depth(node: TreeNode | null): number {
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 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.
As the tree grows, the function visits every node once to calculate depths.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The number of operations grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to find the diameter grows linearly with the number of nodes in the tree.
[X] Wrong: "The function calls depth multiple times per node, so it must be more than linear."
[OK] Correct: Each node is visited once because the recursive calls do not repeat work; results are combined on the way back.
Understanding this helps you explain how recursion can efficiently solve tree problems by visiting nodes once.
"What if we changed the code to calculate depth separately for left and right subtrees multiple times? How would the time complexity change?"
Practice
Solution
Step 1: Understand the diameter definition
The diameter is the longest path between any two nodes, not just from root to leaf.Step 2: Differentiate from other tree properties
Height is longest root-to-leaf path, number of nodes counts all nodes, leaves count only leaf nodes.Final Answer:
The length of the longest path between any two nodes in the tree -> Option DQuick Check:
Diameter = longest path between nodes [OK]
- Confusing diameter with tree height
- Thinking diameter counts nodes instead of edges
- Assuming diameter is from root only
Solution
Step 1: Identify input and output types
The function takes a TreeNode or null and returns a number representing diameter length.Step 2: Match correct signature
function diameter(root: TreeNode | null): number matches input type TreeNode|null and returns number, others mismatch input/output.Final Answer:
function diameter(root: TreeNode | null): number -> Option AQuick Check:
Input: TreeNode|null, Output: number [OK]
- Using wrong input type like number instead of TreeNode
- Returning void instead of number
- Missing null option for empty tree
1 / \ 2 3 / 4
Solution
Step 1: Identify longest path in tree
Longest path is from node 4 to node 3 passing through 2 and 1, length 3 edges.Step 2: Count edges in longest path
Path 4 -> 2 -> 1 -> 3 has 3 edges, so diameter is 3.Final Answer:
3 -> Option BQuick Check:
Longest path edges = 3 [OK]
- Counting nodes instead of edges
- Choosing height instead of diameter
- Ignoring path through root
function diameter(root: TreeNode | null): number {
let maxDiameter = 0;
function depth(node: TreeNode | null): number {
if (!node) return 0;
const left = depth(node.left);
const right = depth(node.right);
maxDiameter = Math.max(maxDiameter, left + right + 1);
return Math.max(left, right) + 1;
}
depth(root);
return maxDiameter;
}Solution
Step 1: Analyze diameter calculation
maxDiameter updates with left + right + 1, counting nodes on path.Step 2: Correct diameter definition
Diameter is number of edges, so subtract 1 from node count to get edges.Final Answer:
Diameter counts nodes, should count edges (subtract 1) -> Option AQuick Check:
Diameter edges = nodes - 1 [OK]
- Confusing nodes count with edges count
- Forgetting to subtract 1 for edges
- Incorrect base case handling
Solution
Step 1: Understand diameter path tracking
During recursion, keep track of nodes on left and right depths to build longest path.Step 2: Modify function to store and return path
Update maxDiameter and store nodes forming longest path, return both diameter and path array.Final Answer:
Track and store nodes on longest path during recursion, return path array with diameter -> Option CQuick Check:
Store nodes during recursion to get path [OK]
- Assuming path cannot be found during recursion
- Trying BFS after diameter calculation only
- Only storing leaf nodes misses full path
Ready to prove it?
Pass the test and this pattern moves unknown
