Skip to main content

Diameter of a Tree

MediumPremium

Given the root of a binary tree, create a function diameterOfTree that determines and returns the length of the diameter of the tree, where the diameter of a tree is defined as the number of nodes along the longest path between any two nodes in the tree.

For example, given the following binary tree:

// tree 1 / \ 2 3 / \ 4 5

The diameter is 4, which is the length of the path [4, 2, 1, 3] or [5, 2, 1, 3].