Problem 466791 · medium · Level 04 Non-Linear Data Structures

Widest Span of a Tree

binary tree · recursion · DFS · post-order

Think of a binary tree as rooms joined by corridors, one corridor for each parent-child link. Pick the two rooms that are farthest apart: the number of corridors between them is the tree's diameter. The longest walk does not have to pass through the root.

Write diameter_of_binary_tree(root) that returns the diameter, counted in edges (corridors), not in nodes.

Examples

      1
    /   \
   2     3
    \   /
     4 5

Input:  root = [1, 2, 3, None, 4, 5]
Output: 4
Explanation: The path 4 -> 2 -> 1 -> 3 -> 5 has 4 edges.
5
 \
  8

Input:  root = [5, None, 8]
Output: 1
Input:  root = [1]
Output: 0

Constraints

  • 1 <= number of nodes <= 1000

Goals

  • Write a helper that returns one value (height) while updating another (best answer) as a side effect
  • Use nonlocal or an instance attribute to share state with a nested function
  • Recognise that the answer may not pass through the root
Starting Python…