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 .
-
Node.value
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
What is the diameter of the following binary tree?
5
/ \
6 7
/ \
8 9
2
3
4
5
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.
Try it yourself
Implement your solution in main.cpp
in the following coding playground.
// 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 treeint DiameterOfBinaryTree(TreeNode<int> *root){// Replace this placeholder return statement with your codereturn -1;}