diameter-of-binary-tree.sh — zsh

Diameter of Binary Tree

easy
binary-treedepth-first-searchrecursion

Given the root of a binary tree, return the length of the diameter of the tree: the number of edges on the longest path between any two nodes. This path may or may not pass through root.

Input / output

  • Input: root: TreeNode (JSON test fixture is a LeetCode-style level-order array, null marks a missing child)
  • Output: int — the number of edges on the longest path

Constraints

  • 0 <= number of nodes <= 10,000
  • -100 <= node value <= 100

Follow-up

Can you compute the diameter in a single O(n) pass instead of recomputing height at every node?

Examples
Example 1
Input: root = [1,2,3,4,5]
Output: 3
Example 2
Input: root = [1,2]
Output: 1
Example 3 (empty tree)
Input: root = []
Output: 0
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.