DIY: Diameter of Binary Tree

Solve the interview question "Diameter of Binary Tree" in this lesson.

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.


The input will be the root node of a binary tree. The following is an example input:

   / \
  2   3
    /  \
   4    5

input = [1]


The output will be an integer value representing the diameter. For the above input, the output will be:


The length of the path [2, 1, 3, 4, 6] is 4.

Coding exercise

Implement the diameterOfBinaryTree(root) function, where root is the root of the binary tree. The function returns an integer value representing the diameter of the tree.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.