1395. The Barycentre Of The Trees


Description

中文English
For a multi-branch tree, if there is a node R with R as the root, and the largest sub-tree of all its sub-trees has the least number of nodes, the node R is said to be the center of gravity of the tree.
Now give you a multi-branch tree with n nodes. Find the center of gravity of this tree. If there are multiple centers of gravity, return the one with the lowest number.
x[i], y[i] represents the two points of the i-th edge.

  • 2 <= n <= 10^5
  • 1 <= x[i], y[i] <= n

Example

Example 1:
Given x = `[1]`, y = `[2]`, return `1`.
Input:
[1]
[2]
Output:
1

Explanation:
Both 1 and 2 can be center of gravity, but the number of 1 is the smallest.
Example 2:
Given x = `[1,2,2]`, y = `[2,3,4]`, return `2`.
Input:
[1,2,2]
[2,3,4]
Output:
2

Explanation:
2 is the center of gravity.
Code(Language:C++)
class Solution {
public:
    /**
     * @param x: The vertexes of the edges
     * @param y: The vertexes of the edges
     * @return: Return the index of barycentre
     */
    void dfs(int x, int f, int &n, int &ansNode, int &ansSize, vector<int> &dp, vector<vector<int>> &tree) {
        dp[x] = 1;
        int maxSubtree = 0;
        for (int i = 0; i < tree[x].size(); i++) {
            int y = tree[x][i];
            if (y == f) {
                continue;
            }
            dfs(y, x, n, ansNode, ansSize, dp, tree);
            dp[x] += dp[y];
            maxSubtree = max(maxSubtree, dp[y]);
        }
        maxSubtree = max(maxSubtree, n - dp[x]);
        if (maxSubtree < ansSize || (maxSubtree == ansSize && x < ansNode)) {
            ansNode = x;
            ansSize = maxSubtree;
        }
    }
    int getBarycentre(vector<int> &x, vector<int> &y) {
        // Write your code here
        int n = x.size() + 1;
        vector<vector<int>> tree(n + 1);
        vector<int> dp(n + 1);
        for (int i = 0; i < x.size(); i++) {
            tree[x[i]].push_back(y[i]);
            tree[y[i]].push_back(x[i]);
        }
        int ansNode = 0;
        int ansSize = n + 1;
        dfs(1, 0, n, ansNode, ansSize, dp, tree);
        return ansNode;
    }
};

Comments

Popular posts from this blog

Amazon OA 763. Partition Labels

1427. Split Array into Fibonacci Sequence