Centroid
Definition
In a tree , a centroid is a node which if we remove (remove it and remove all edges from this node) , the maximum size of the trees in the newly created forest will be the minimum .
The implementation is straightfowrad . Just implement according to the definition .
1 | Step 1 : Find the size of all subtrees connected to a vertex |
1 | void dfs(int u,int p) |
Extended Definition
In a tree , a centroid is a node which if we remove (remove it and remove all edges from this node) , the size of the trees in the newly created forest will be atmost N/2
This definition actually gives what the size of the trees in the newly created forest will . It will be atmost N/2
Implementation using this extended definition .
1 | void dfs(int u,int p,vector<int>¢roids) |
Number of Centroids
We can see that if we remove the centroid , each of the trees in the remaining forest can have atmost N/2
nodes .
Now consider this 2 cases :
Case 1
Subtree size of centroid > N/2
This case we can not have more than one centroid because if there were to have another centroid , this component of the first centroid ( which has subtree size > N/2
) will have more than N/2
nodes . And thus defying the condition to be a centroid . So , we can not have more than 1 centroids in this case .
Case 2
Subtree size of centroid = N/2
In this case , the size of the component including the parent of this centroid will also be N/2
. Thus , we can get 2 centroids in this case
So , we can have atmost 2
centroids in a tree