End of Year Sale: Use Coupon Code END2025 to Get Extra 25% Off.
12DAYS
:
21HOURS
:
04MINUTES
:
53SECONDS
Leetcode Problem 1245. Tree Diameter
1245. Tree Diameter
Leetcode Solutions
Approach: Farthest Nodes via BFS
Convert the edge list into an adjacency list to represent the tree as a graph.
Perform BFS starting from an arbitrary node (e.g., node 0) to find the farthest node from it. Keep track of the visited nodes and the distance from the starting node.
Perform BFS a second time starting from the farthest node found in step 2. Again, keep track of the visited nodes and the distance from the starting node.
The maximum distance found in the second BFS is the diameter of the tree.