bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1245. Tree Diameter

1245. Tree Diameter

Leetcode Solutions

Approach: Farthest Nodes via BFS

  1. Convert the edge list into an adjacency list to represent the tree as a graph.
  2. 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.
  3. 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.
  4. The maximum distance found in the second BFS is the diameter of the tree.
UML Thumbnail

Approach: DFS (Depth-First Search)

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...