Given an undirected tree, we need to find the longest path of this tree where a path is defined as a sequence of nodes.
Input : Below shown Tree using adjacency list representation: Output : 5 In below tree longest path is of length 5 from node 5 to node 7
In this post, an efficient solution is discussed. We can find longest path using two BFSs. The idea is based on the following fact: If we start BFS from any node x and find a node with the longest distance from x, it must be an end point of the longest path. It can be proved using contradiction. So our algorithm reduces to simple two BFSs. First BFS to find an end point of the longest path and second BFS from this end point to find the actual longest path. For the proof of why does this algorithm works, there is nice explanation here Proof of correctness: Algorithm for diameter of a tree in graph theory
As we can see in above diagram, if we start our BFS from node-0, the node at the farthest distance from it will be node-5, now if we start our BFS from node-5 the node at the farthest distance will be node-7, finally, path from node-5 to node-7 will constitute our longest path.
Longest path is from 5 to 7 of length 5
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Longest Path with Same Values in a Binary Tree
- Print the longest leaf to leaf path in a Binary tree
- Minimum distance to visit all the nodes of an undirected weighted tree
- Sum of nodes on the longest path from root to leaf node
- Reverse tree path
- Maximum Path Sum in a Binary Tree
- Reverse tree path using Queue
- XOR of path between any two nodes in a Binary Tree
- GCD from root to leaf path in an N-ary tree
- Maximum XOR with given value in the path from root to given node in the tree
- Print path between any two nodes in a Binary Tree
- Minimum sum path between two leaves of a binary tree
- Assign weights to edges such that longest path in terms of weights is minimized
- Find the maximum path sum between two leaves of a binary tree
- Print path from root to a given node in a binary tree
Improved By : Brij Raj Kishore