CodeArchon

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.

1def diameterOfBinaryTree(root: Optional[TreeNode]) -> int:
2 diameter = 0
3 def height(node: Optional[TreeNode]) -> int:
4 nonlocal diameter
5 if not node:
6 return 0
7 l = height(node.left)
8 r = height(node.right)
9 diameter = max(diameter, l + r)
10 return 1 + max(l, r)
11 height(root)
12 return diameter
Variables
curr=1
currentMaxDiameter=0

How to think about it

  1. Diameter is not guaranteed to pass through the root.
  2. Therefore, count left_height + right_height at each candidate node.
  3. 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 13
{"arr":[1,2,3,4,5]}

Path is [4,2,1,3] or [5,2,1,3], length 3 edges.

Example 21
{"arr":[1,2]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed