1659. Tree Centre of Weight
A network of n servers, numbered 0 to n-1, is wired as a tree: edges lists the n-1 cables as pairs [u, v]. If one server is unplugged, the remaining servers split into groups that are still connected to each other. Call a server a balance point when, after unplugging it, no group holds more than n/2 servers (compare 2 * size <= n).
Return all balance points as an array of server numbers in ascending order. Every tree has one or two of them. A single server (n = 1) is its own balance point. Aim for O(n) time and O(n) space: one traversal that computes subtree sizes is enough, and re-splitting the network for every server is far too slow.
Example 1
- Input:
- n = 4, edges = [[0,1],[1,2],[2,3]]
- Output:
- [1,2]
- Explanation:
Removing node 1 leaves parts of size 1 and 2, both at most 2, and the same holds for node 2, so both middle nodes are centres.
Example 2
- Input:
- n = 5, edges = [[0,1],[0,2],[0,3],[0,4]]
- Output:
- [0]
- Explanation:
Removing the hub 0 leaves four single nodes, while removing any leaf leaves a part of size 4 > 2.
Constraints
1 ≤ n ≤ 105
edges.length == n - 1 and the edges form a tree on nodes 0..n-1
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)