algorythms
Tree DFS
LC #543Easy

Diameter of Binary Tree

Tree DFS
AmazonGoogleMetaBloomberg

Problem

Find the length of the longest path between any two nodes in the tree (the diameter).

treedfs

Constraints

  • 1 ≤ n ≤ 10⁴
  • -100 ≤ Node.val ≤ 100
  • Path does not need to pass through root

Example

Inputroot = [1, 2, 3, 4, 5]
Output3
Why

Longest path is [4,2,1,3] or [5,2,1,3], length = 3 edges

Hints — reveal one at a time