easyTreesGoogleAmazonAppleMeta
Signal Span Router
A computer network analyst measures the largest communication latency (diameter) in a decentralized hub topology.
Given the root of a binary tree, return the length of the diameter of the tree. The diameter is the length of the longest path between any two nodes in a tree, represented by the number of edges between them.
Choose approach
1
curr
2
3
4
5
1/11
Narrationstep 1 of 11
Compute subtrees height for 1.
Variables
curr=1
currentMaxDiameter=0
How to think about it
- Diameter is not guaranteed to pass through the root.
- Therefore, count left_height + right_height at each candidate node.
- Return node_height (1 + max(left, right)) upward.
Edge cases to catch in interview
- Linear tree -> diameter is n-1.
- Single node -> 0 edges diameter.
Examples
Example 1
3{"arr":[1,2,3,4,5]}
Path is [4,2,1,3] or [5,2,1,3], length 3 edges.
Example 2
1{"arr":[1,2]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed