Diameter of Binary Tree in DSA Java - Time & Space Complexity
We want to know how long it takes to find the diameter of a binary tree 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.
public class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}
public class Solution {
int diameter = 0;
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return diameter;
}
private int depth(TreeNode node) {
if (node == null) return 0;
int left = depth(node.left);
int right = depth(node.right);
diameter = Math.max(diameter, left + right);
return Math.max(left, right) + 1;
}
}
This code finds the longest path between any two nodes in a binary tree by checking depths of subtrees.
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 number of nodes grows, the function visits each 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 work grows directly with the number of nodes, so doubling nodes doubles work.
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 code visits nodes multiple times, so time is more than linear."
[OK] Correct: Each node is visited once in the recursion, and depth is calculated on the way back, so no repeated full visits.
Understanding this linear time approach shows you can handle tree problems efficiently, a key skill in many coding challenges.
"What if we changed the code to calculate diameter by checking all pairs of nodes? How would the time complexity change?"
Practice
Solution
Step 1: Understand the diameter definition
The diameter is the longest path between any two nodes, which may or may not pass through the root.Step 2: Differentiate from other tree properties
Height is the longest path from root to leaf, leaf count is number of leaves, total nodes is size, none of which define diameter.Final Answer:
The length of the longest path between any two nodes in the tree -> Option BQuick Check:
Diameter = Longest path between nodes [OK]
- Confusing diameter with height
- Thinking diameter counts nodes instead of edges
- Assuming diameter must pass through root
Solution
Step 1: Identify correct parameter type
The method must accept a TreeNode object representing the root of the tree or subtree.Step 2: Identify correct return type
Diameter is a number (int), so return type should be int, not void or String.Final Answer:
public int diameter(TreeNode root) -> Option DQuick Check:
Method returns int and takes TreeNode [OK]
- Using void return type for diameter
- Passing int instead of TreeNode
- Returning String instead of int
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}
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);
// Diameter calculation code omitted for brevity
Solution
Step 1: Visualize the tree structure
The tree has root 1, left child 2 with children 4 and 5, and right child 3.Step 2: Find longest path between any two nodes
Longest path is from node 4 to node 3 via 2 and 1: path 4->2->1->3 = 3 edges, diameter = 3.Final Answer:
3 -> Option CQuick Check:
Longest path length = 3 edges [OK]
- Counting nodes instead of edges or vice versa
- Ignoring paths not passing through root
- Miscounting edges in path
int diameter = 0;
int height(TreeNode root) {
if (root == null) return 0;
int left = height(root.left);
int right = height(root.right);
diameter = Math.max(diameter, left + right);
return Math.max(left, right);
}Solution
Step 1: Understand height calculation
Height of a node is 1 plus max height of its children, so must add +1.Step 2: Identify bug in return statement
Current code returns max(left, right) without +1, so height is underestimated.Final Answer:
Return Math.max(left, right) + 1 instead of Math.max(left, right) -> Option AQuick Check:
Height = max child height + 1 [OK]
- Forgetting to add +1 in height return
- Using min instead of max for diameter update
- Returning sum of left and right as height
Solution
Step 1: Understand diameter and path relationship
Diameter is longest path length; to print nodes, we must track path during diameter calculation.Step 2: Choose approach that combines diameter and path tracking
Modifying diameter function to store nodes on longest path is efficient and direct.Final Answer:
Modify the diameter function to store and return the longest path nodes along with diameter -> Option AQuick Check:
Track path during diameter calc for nodes [OK]
- Running BFS separately wastes time
- Assuming height equals diameter path
- Counting leaves without path tracking
Ready to prove it?
Pass the test and this pattern moves unknown
