AlgoDaily

Diameter of Binary Tree

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Diameter of Binary Tree

Diameter of Binary Tree

Let's find out the length of the diameter of the tree!

This is a simple binary tree question that is frequently asked in interviews. So let's see how we can solve this problem.

Prompt

Given the root of a binary tree, return the length of the diameter of the tree.

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Note: The length of a path between two nodes is represented by the number of edges between them.

Problem Statement

Given the Binary Tree above as the problem where,

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

Output: length = 3

We get to solution three by taking the paths a, b, and c or d, b, and c, as shown in the image below:

Problem Statement2

Constraints

  • The number of nodes in the tree is in the range [1, 10^4) ].
  • -100 <= Node.val <= 100

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →