educative.io

Educative

Diameter of a tree is between two leaf nodes and not any two nodes

Hi,

The diameter of a tree is defined as : the number of nodes on the “longest path between any two leaf nodes”, so if I have the following example:
root = 1
root.left = 2
root.left.left = 4

As per the definition of diameter, the output be should’ve been 0 (since there are no two leaf nodes present) instead of 3, because the tree is rooted at 1 and 1 isn’t leaf node.

So, how would you update the program to get longest path between two LEAF nodes only?

Thank you,
Rohan

Instead of:

diameter = leftTreeHeight + rightTreeHeight + 1

we can do:

diameter = 0
if leftTreeHeight != 0 and rightTreeHeight != 0:
    diameter = leftTreeHeight + rightTreeHeight + 1