Good afternoon! Here's our prompt for today.
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.

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:
.png)
Constraints
- The number of nodes in the tree is in the range
[1, 10^4) ]
. -100 <= Node.val <= 100
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
class Node{
constructor(value){
this.value = value
this.left = null
this.right = null
}
}
function height(tnode)
{
if(tnode == null)
return 0
return 1 + Math.max(height(tnode.left), height(tnode.right))
}
function diameter_maxdepth(root_node){
//Enter your code here
}
​
​
tree1 = new Node(1)
tree1.left = new Node(2)
tree1.right = new Node(3)
tree1.left.left = new Node(4)
tree1.left.right = new Node(5)
​
​
tree2 = new Node(1)
tree2.left = new Node(2)
tree2.right = new Node(3)
Here's our guided, illustrated walk-through.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.