All problems
Tree Centroid Find
Problem
Find a centroid of a tree with n nodes: a node whose removal leaves components of size at most n/2.
For every candidate root compute subtree sizes and the largest resulting component; return the candidate with the smallest largest component, breaking ties by smallest index. edges is a list of [u, v] pairs.
Hint
A tree has one centroid or two adjacent centroids.
Test cases
case 1
in: [4,[[0,1],[1,2],[2,3]]]
expected: 1
case 2
in: [4,[[0,1],[0,2],[0,3]]]
expected: 0
case 3
in: [5,[[0,1],[1,2],[2,3],[3,4]]]
expected: 2
case 4
in: [3,[[0,1],[1,2]]]
expected: 1
Starter codePython
def tree_centroid(n, edges):
# Your code here
pass4 test cases · run your code against them in the editor