Diameter of Binary Tree in DSA Go - 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 number of steps grow when the tree has more nodes?
Analyze the time complexity of the following code snippet.
func diameterOfBinaryTree(root *TreeNode) int {
maxDiameter := 0
var depth func(node *TreeNode) int
depth = func(node *TreeNode) int {
if node == nil {
return 0
}
left := depth(node.Left)
right := depth(node.Right)
if left+right > maxDiameter {
maxDiameter = left + right
}
if left > right {
return left + 1
}
return right + 1
}
depth(root)
return maxDiameter
}
This code finds the longest path between any two nodes in a binary tree by calculating depths recursively.
- Primary operation: Recursive calls to visit each node once.
- How many times: Each node is visited exactly one time.
As the number of nodes (n) increases, the function visits each node once to calculate depths.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 recursive calls |
| 100 | About 100 recursive calls |
| 1000 | About 1000 recursive calls |
Pattern observation: The number of operations grows roughly in direct proportion to 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 visits nodes multiple times, so time is more than linear."
[OK] Correct: Each node is visited once during the depth calculation, so the total work is proportional to the number of nodes.
Understanding this linear time complexity helps you explain efficient tree traversal and recursion in interviews confidently.
"What if the tree was skewed (like a linked list)? How would the time complexity change?"