centroid of a tree

Solutions on MaxInterview for centroid of a tree by the best coders in the world

showing results for - "centroid of a tree"
Alan
05 Aug 2019
1vector<int> Centroid(const vector<vector<int>> &g) {
2        int n = g.size();
3        vector<int> centroid;
4        vector<int> sz(n);
5        function<void (int, int)> dfs = [&](int u, int prev) {
6                sz[u] = 1;
7                bool is_centroid = true;
8                for (auto v : g[u]) if (v != prev) {
9                        dfs(v, u);
10                        sz[u] += sz[v];
11                        if (sz[v] > n / 2) is_centroid = false;
12                }
13                if (n - sz[u] > n / 2) is_centroid = false;
14                if (is_centroid) centroid.push_back(u);
15        };
16        dfs(0, -1);
17        return centroid;
18}