Asked at

Diameter Of Binary Tree

Medium
Verified
TreeDFSRecursion~20 min

Given the root of a binary tree, return its diameter: the number of edges on the longest path between any two nodes.

The path may or may not pass through the root. A node is { val, left, right } with null children; the whole empty tree is null. The input arrives as the root node directly.

Examples

in{val:1, left:{val:2, left:{val:4}, right:{val:5}}, right:{val:3}}
out3

Longest path 4 → 2 → 1 → 3 spans 3 edges.

in{val:1, left:null, right:null}
out0

A single node has no edges.

Constraints

  • 1 ≤ number of nodes ≤ 10⁴
  • -100 ≤ node.val ≤ 100

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.