Skip to content
BASA DSA

Diameter of Binary Tree

EasyTrees

Return the largest number of edges in any path between two nodes of a binary tree. The path need not pass through the root.

Example 1

Argument 1 tree: level-order input; omitted children are null.Argument 1 tree: level-order input; omitted children are null. Vertices: node 0: 1, node 1: 2, node 2: 3, node 3: 4, node 4: 5. Edges: node 0 (1) — node 1 (2) left child; node 0 (1) — node 2 (3) right child; node 1 (2) — node 3 (4) left child; node 1 (2) — node 4 (5) right child.12345
Argument 1 tree: level-order input; omitted children are null.

Input
root = [1,2,3,4,5]
Output
3

Explanation

4->2->1->3 has three edges; diameter counts edges rather than nodes.

Example 2

Argument 1 tree: level-order input; omitted children are null.Argument 1 tree: level-order input; omitted children are null. Vertices: node 0: 1. Edges: none.1
Argument 1 tree: level-order input; omitted children are null.

Input
root = [1]
Output
0

Explanation

A single node has no edge, giving diameter zero.

Example 3

Argument 1 tree: empty tree (null root).
Input
root = []
Output
0

Explanation

An empty tree has no path edge to count.

Constraints

  • 0 <= number of nodes <= 10000
  • Trees are breadth-first arrays with null holes

Function contractdiameterOfBinaryTreeArguments: tree
Loading draft…
SolutionRuns on your device
Loading draft…