Problem Description
Given an undirected tree with n nodes (labeled from 0 to n-1) represented by an array of edges, determine the diameter of the tree, which is defined as the number of edges in the longest path in the tree.
Key Insights
- The tree diameter is the longest path between any two nodes.
- A two-pass DFS/BFS approach can be used:
- First, pick an arbitrary node and find the farthest node from it.
- Second, from that farthest node, compute the maximum distance to any other node.
- This method works because the longest path of a tree always starts at a leaf and ends at a leaf.
Space and Time Complexity
Time Complexity: O(n) – Each node is visited once in each DFS/BFS pass.
Space Complexity: O(n) – The graph adjacency list and recursion/queue may hold up to n nodes.
Solution
We solve the problem using a two-pass depth-first search (DFS) approach. First, we start from an arbitrary node (e.g., node 0) and perform a DFS to locate the node farthest from it. Then, we perform a second DFS starting from this farthest node to compute the maximum distance to any other node, which is the tree's diameter. The tree is represented as an adjacency list, and the DFS tracks the current distance and the parent node to avoid cycles. This solution efficiently computes the desired result with a linear runtime relative to n, leveraging the tree structure properties.