...

/

Diameter of Binary Tree

Diameter of Binary Tree

Try to solve the Diameter of Binary Tree problem.

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

C++
usercode > main.cpp
// Definition for a binary tree node
// template<class T>
// class TreeNode {
// public:
// T data;
// TreeNode<T>* left;
// TreeNode<T>* right;
// TreeNode(const T data) : data(data), left(nullptr), right(nullptr) {}
// };
// DiameterOfBinaryTree returns the diameter of tree
int DiameterOfBinaryTree(TreeNode<int> *root)
{
// Replace this placeholder return statement with your code
return -1;
}
Diameter of Binary Tree

Access this course and 1200+ top-rated courses and projects.