Compute tree diameter
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of binary tree algorithms, recursion versus iterative traversal strategies, and competence in algorithmic analysis including time and space complexity and handling deep-recursion stack overflow when computing a tree's diameter.
Constraints
- 0 <= number of nodes <= 10^5
- The tree may be highly unbalanced (effectively a linked list of depth up to n), so a naive recursive solution can overflow the call stack.
- Node values fit in a 32-bit signed integer and do not affect the diameter.
- An empty tree or a single node has diameter 0.
Examples
Input: ([1, 2, 3, 4, 5],)
Expected Output: 3
Explanation: Tree is 1 with children 2,3 and 2 with children 4,5. Longest path 4-2-1-3 has 3 edges; it bends at node 1 but does not extend to a deeper leaf, so the diameter is 3.
Input: ([1, 2, None, 3, None, 4, None, 5],)
Expected Output: 4
Explanation: A left-skewed chain 1-2-3-4-5 (each node has only a left child). The longest path runs end to end with 4 edges, exercising the deep-tree case.
Input: ([1],)
Expected Output: 0
Explanation: A single node has no edges, so the diameter is 0.
Input: ([],)
Expected Output: 0
Explanation: An empty tree has diameter 0.
Input: ([1, 2, 3],)
Expected Output: 2
Explanation: Perfectly balanced 3-node tree. Path 2-1-3 has 2 edges.
Input: ([1, None, 2, None, 3],)
Expected Output: 2
Explanation: A right-skewed chain 1-2-3 has 2 edges, the mirror of the left-skewed case.
Hints
- The diameter at a node equals leftHeight + rightHeight (counting edges). Track a running maximum of this quantity while you also return each subtree's height.
- Heights are needed bottom-up, so compute them in a post-order traversal: a node can only be finalized after both its children are done.
- To survive very deep trees, replace recursion with an explicit stack (push each node twice — once to descend, once to process) so the OS call stack is never the bottleneck.