Search⌘ K
AI Features

Diameter of Binary Tree

Diameter of Binary Tree asks you to find the length of the longest path between any two nodes, measured in edges, whether or not the path passes through the root.

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.go in the following coding playground.

Go
usercode > main.go
package main
import (. "golang-test-code/ds_v1/BinaryTree") // TreeNode[T]
// Definition of a binary tree node
// type TreeNode[T any] struct {
// Data T
// Left *TreeNode[T]
// Right *TreeNode[T]
// }
func diameterOfBinaryTree(root *TreeNode[int]) int{
// Replace this placeholder return statement with your code
return -1
}
Diameter of Binary Tree