Tree Distances I
You are given an undirected tree with n nodes labeled from 1 to n.
For each node, determine the maximum distance from that node to any other node in the tree.
The distance between two nodes is the number of edges in the shortest path between them.
Return an array where the ith value represents the maximum distance from node i to any other node.
Example 1:
Input: n = 5, edges = [[1,2],[1,3],[3,4],[3,5]]
Output: [2,3,2,3,3]
Explanation:
- For node 1, the farthest node is 4 or 5, so the maximum distance is 2.
- For node 2, the farthest node is 4 or 5, so the maximum distance is 3.
- For node 3, the farthest node is 2, so the maximum distance is 2.
- For node 4, the farthest node is 2, so the maximum distance is 3.
- For node 5, the farthest node is 2, so the maximum distance is 3.
Example 2:
Input: n = 6, edges = [[1,2],[2,3],[3,4],[4,5],[5,6]]
Output: [5,4,3,3,4,5]
Explanation:
- This tree is a straight path.
- From node 1, the farthest node is 6, so the distance is 5.
- From node 2, the farthest node is 6, so the distance is 4.
- From node 3, the farthest node is 6, so the distance is 3.
- From node 4, the farthest node is 1, so the distance is 3.
- From node 5, the farthest node is 1, so the distance is 4.
- From node 6, the farthest node is 1, so the distance is 5.
Now Your Turn!
Pick the correct output for the given inputInput: n = 4, edges = [[1,2],[2,3],[3,4]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n <= 2 * 105
- edges.length == n - 1
- edges[i].length == 2
- 1 <= edges[i][0], edges[i][1] <= n
- edges represents a valid tree