Diameter of Binary Tree in DSA C++ - Time & Space Complexity
We want to understand how the time needed to find the diameter of a binary tree changes as the tree grows.
The question is: how does the work increase when the tree has more nodes?
Analyze the time complexity of the following code snippet.
int height(TreeNode* root) {
if (!root) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + max(leftHeight, rightHeight);
}
int diameter(TreeNode* root) {
if (!root) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
int leftDiameter = diameter(root->left);
int rightDiameter = diameter(root->right);
return max(leftHeight + rightHeight, max(leftDiameter, rightDiameter));
}
This code finds the diameter by computing heights and diameters of subtrees recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls to height and diameter functions.
- How many times: For each node, height is called multiple times leading to repeated work.
As the number of nodes (n) increases, the height function is called many times for the same nodes, causing repeated work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | ~100 calls |
| 100 | ~10,000 calls |
| 1000 | ~1,000,000 calls |
Pattern observation: The work grows roughly with the square of the number of nodes because height is recomputed many times.
Time Complexity: O(n²)
This means the time needed grows roughly with the square of the number of nodes in the tree.
[X] Wrong: "The diameter function runs in linear time because it visits each node once."
[OK] Correct: The height function is called repeatedly for the same nodes, causing extra work that adds up to quadratic time.
Understanding this helps you explain why naive recursive solutions can be slow and how to improve them, a key skill in interviews.
"What if we compute height once for each node and store it? 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 height and node count
Height is longest root-to-leaf path; node count and leaf count are unrelated to diameter.Final Answer:
The longest path between any two nodes in the tree -> Option AQuick Check:
Diameter = longest node-to-node path [OK]
- Confusing diameter with tree height
- Thinking diameter counts nodes instead of edges
- Assuming diameter is number of leaf nodes
Solution
Step 1: Understand pointer usage in tree nodes
Binary trees are usually handled with pointers to nodes, so TreeNode* is correct.Step 2: Check return type and parameter correctness
Diameter returns an int, and parameter should be pointer, not value or reference for typical tree traversal.Final Answer:
int diameter(TreeNode* root); -> Option DQuick Check:
Pointer parameter with int return [OK]
- Passing node by value instead of pointer
- Using void return type instead of int
- Passing node by reference unnecessarily
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int height(TreeNode* root) {
if (!root) return 0;
return 1 + std::max(height(root->left), height(root->right));
}
int diameter(TreeNode* root) {
if (!root) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
int leftDiameter = diameter(root->left);
int rightDiameter = diameter(root->right);
return std::max(leftHeight + rightHeight, std::max(leftDiameter, rightDiameter));
}
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
std::cout << diameter(root);
return 0;
}Solution
Step 1: Calculate heights of left and right subtrees
Left subtree height: max height of nodes 2->4 or 2->5 is 2; right subtree height (node 3) is 1.Step 2: Calculate diameter candidates and choose max
Diameter candidates: leftHeight + rightHeight = 2 + 1 = 3; leftDiameter and rightDiameter are computed recursively. LeftDiameter is 2 (path 4-2-5), rightDiameter is 0. Max is 3.Final Answer:
3 -> Option CQuick Check:
Longest path length = 3 edges [OK]
- Confusing height with diameter
- Counting nodes instead of edges
- Ignoring recursive diameter calls
int diameter(TreeNode* root) {
if (!root) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
int leftDiameter = diameter(root->left);
int rightDiameter = diameter(root->right);
return leftHeight + rightHeight;
}Solution
Step 1: Analyze current return statement
Currently returns only leftHeight + rightHeight, ignoring recursive diameters from subtrees.Step 2: Correct return to consider all diameter candidates
Diameter is max of leftHeight + rightHeight, leftDiameter, and rightDiameter.Final Answer:
Return max of leftHeight + rightHeight and leftDiameter, rightDiameter -> Option BQuick Check:
Include all diameter candidates [OK]
- Ignoring recursive diameter calls
- Returning sum of diameters incorrectly
- Returning height instead of diameter
Solution
Step 1: Modify height to return max sum of node values
Instead of counting edges, height returns max sum from node to leaf including node values.Step 2: Update diameter to use sums from left and right subtrees
Diameter becomes max of left sum + right sum and recursive diameters, reflecting max path sum.Final Answer:
Change height function to return max sum of node values and update diameter to use sums instead of heights -> Option AQuick Check:
Use sums in height and diameter for max path value [OK]
- Multiplying diameter by node values incorrectly
- Adding all node values regardless of path
- Returning max node value instead of path sum
Ready to prove it?
Pass the test and this pattern moves unknown
