Problem
There exists an undirected tree with n
nodes numbered 0
to n - 1
.
You are given a 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi]
indicates that there is an edge between nodes ui
and vi
in the tree.
Initially, all nodes are unmarked. After every second, you mark all unmarked nodes which have at least one marked node adjacent to them.
Return an array nodes
where nodes[i]
is the last node to get marked in the tree, if you mark node i
at time t = 0
. If nodes[i]
has multiple answers for any node i
, you can chooseany one answer.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
2 <= n <= 10^5
edges.length == n - 1
edges[i].length == 2
0 <= edges[i][0], edges[i][1] <= n - 1
- The input is generated such that
edges
represents a valid tree.
Solution
Method 1 – Farthest Node by BFS (Tree Diameter)
Intuition
When marking starts from a node, the last node to be marked is the farthest from the starting node. In a tree, this is always a leaf at the maximum distance. For each node, the answer is any node at the farthest distance from it.
Approach
- Build the adjacency list for the tree.
- For each node, run BFS to find the farthest node from it (the last to be marked).
- For efficiency, precompute the two endpoints of the tree’s diameter (longest path in the tree).
- For each node, the farthest node is always one of the two diameter endpoints.
- For each node, compare its distance to both endpoints and pick the farther one.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, as each BFS traverses all nodes and we do three BFS. - 🧺 Space complexity:
O(n)
, for adjacency list and distance arrays.