Search⌘ K
AI Features

Diameter of Binary Tree

Explore how to calculate the diameter of a binary tree by identifying the longest path between any two nodes. This lesson helps you understand tree structures using depth-first search to solve binary tree problems effectively. You will practice implementing and optimizing your solution within given constraints.

Statement

Given a binary tree, you need to compute the length of the tree’s diameter. 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 the path between two nodes is represented by the number of edges between them.

Constraints:

  • The number of nodes in the tree is in the range [1,500][1, 500].
  • 100-100 \leq Node.value 100\leq 100

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Diameter of Binary Tree

1.

What is the diameter of the following binary tree?

  5
 / \
6   7
   / \
  8   9
A.

2

B.

3

C.

4

D.

5


1 / 4

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4

Try it yourself

Implement your solution in main.java in the following coding playground.

Java
usercode > Solution.java
import java.util.*;
import ds_v1.BinaryTree.TreeNode;
// Definiton of a binary tree node class
// class TreeNode<T> {
// T data;
// TreeNode<T> left;
// TreeNode<T> right;
// TreeNode(T data) {
// this.data = data;
// this.left = null;
// this.right = null;
// }
// }
public class Solution{
public static int diameterOfBinaryTree(TreeNode<Integer> root) {
// Replace this placeholder return statement with your code
return -1;
}
}
Diameter of Binary Tree