Press "Enter" to skip to content

Find Longest Path in Tree

Ajk 0

Today’s question is going to be a quick one. We want to find longest path in tree. What does Path mean in a Tree context?
The Tree wikipedia page and Tree/Graph Theory shed some light.

Longest Path is the longest path from any two nodes in a tree.

Diameter is the longest path from any two nodes in a tree/graph.

Hence it seems like we want to find longest path in tree, which is also called diameter of the tree.

Below is my code which takes time-complexity O(n) thanks to computing height and diameter at the same time.

Well in the comfort of my home, I came up with this code in 5 mins.
Hope you guys enjoyed it… and I’ll see you guys next time!

The following two tabs change content below.
If you like one of my posts the best way to support is give it a thumbs up, comment, or share it on social media 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *