Diameter of Binary Tree
Easy · Trees
You are given the root of a binary tree. Find the longest path between any two nodes in the tree, where the path does not need to pass through the root. Return the length of this longest path, measured as the number of edges on it.
Examples
Input: root = [1,2,3,4,5]
Output: 3
Why: The longest path goes from node 4 through node 2 through node 1 to node 3, covering 3 edges.
Input: root = [1,2]
Output: 1
Why: There is only one edge in the whole tree, connecting node 1 and node 2.
Input: root = [1]
Output: 0
Why: A single node has no edges, so the diameter is 0.
Constraints
the number of nodes is between 1 and 10^4, and each node value is between -100 and 100
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
Practise Diameter of Binary Tree
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Diameter of Binary Tree. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.