Find the Last Marked Nodes in Tree - Problem
Imagine a viral spread simulation on a tree network! You have an undirected tree with n nodes numbered from 0 to n-1, connected by n-1 edges.
Here's how the simulation works:
- At time
t = 0, you mark exactly one node as the initial infection source - Every second after that, the infection spreads to all unmarked nodes that are adjacent to any already marked node
- This continues until every node in the tree is marked
Your task: For each possible starting node i, determine which node will be the very last to get marked. Return an array where result[i] is the last node to be marked when starting from node i.
Note: If there are multiple nodes that could be last (tied for the same time), you can return any of them.
Input & Output
example_1.py — Basic Tree
$
Input:
edges = [[0,1],[0,2],[1,3]]
›
Output:
[3, 2, 3, 2]
💡 Note:
Tree: 2-0-1-3. Starting from 0: node 3 is farthest. Starting from 1: node 2 is farthest (distance 3). Starting from 2: node 3 is farthest (distance 3). Starting from 3: node 2 is farthest (distance 3).
example_2.py — Linear Tree
$
Input:
edges = [[0,1],[1,2],[2,3],[3,4]]
›
Output:
[4, 4, 4, 0, 0]
💡 Note:
Linear tree: 0-1-2-3-4. When starting from nodes 0,1,2, node 4 is farthest. When starting from nodes 3,4, node 0 is farthest.
example_3.py — Single Node
$
Input:
edges = []
›
Output:
[0]
💡 Note:
Only one node exists (node 0), so when starting from node 0, node 0 itself is the last (and only) node to be marked.
Constraints
- 1 ≤ n ≤ 105
- edges.length == n - 1
- 0 ≤ ui, vi < n
- The input represents a valid tree (connected and acyclic)
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code