Diameter of a Binary Tree

0

0 votes
Binary tree, Tree
Problem

The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. The diagram below shows two trees each with diameter nine, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes). 

Diameter of Binary Tree Example

You need to complete the function diameterOfBinaryTree() that takes root node and total number of nodes in the tree as input and return as output a single integer i.e. the diameter of the tree

Input:

You don't need to input anything. You just need to complete the function diameterOfBinaryTree(). It has two parameters: number of nodes (integer) and root of the tree.

Output:

The function should return a single integer i.e. the diameter of the tree

Constraints:

1 <= number of testcases <= 250

1 <= number of nodes <= 900

-5000 <= node values <= 5000

Time Limit: 0.1
Memory Limit: 256
Source Limit:
Explanation

Test Case 1:

   1    

  /  \

2    3

Path: 2 - 1 - 3

Test Case 2:

     10       

     /   \     

   20    30   

  /   \   

40   60

Path: 40 - 20 - 10 - 30

Test Case 3:

     1

        \

         5

        /

      4

     / \

    3 5

  /

1

Path: 1 - 5 - 4 - 3 -1

 

Editor Image

?