LeetCode #834 Sum of Distances in Tree 树中距离之和

834 Sum of Distances in Tree 树中距离之和

Description:
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.

You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.

Example:

Example 1:

lc-sumdist1

Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.

Example 2:

lc-sumdist2

Input: n = 1, edges = []
Output: [0]

Example 3:

lc-sumdist3

Input: n = 2, edges = [[1,0]]
Output: [1,1]

Constraints:

1 <= n <= 3 * 10^4
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
The given input represents a valid tree.

题目描述:
给定一个无向、连通的树。树中有 N 个标记为 0...N-1 的节点以及 N-1 条边 。

第 i 条边连接节点 edges[i][0] 和 edges[i][1] 。

返回一个表示节点 i 与其他所有节点距离之和的列表 ans。

示例 :

示例 1:

输入: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
输出: [8,12,6,10,10,10]
解释:
如下为给定的树的示意图:

  0
 / \
1   2
   /|\
  3 4 5

我们可以计算出 dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
也就是 1 + 1 + 2 + 2 + 2 = 8。 因此,answer[0] = 8,以此类推。

说明:
1 <= N <= 10000

思路:

树形 DP
用一个数组 nodes 记录子结点数, 每个结点初始化为 1
dp[i] 表示到 i 各结点的距离之和, 每个结点初始化为 0
先用后序遍历, 得到所有的结点的子结点数
在后序遍历的同时, dp[i] 加上子结点的距离 dp[i] += dp[child] + nodes[child], 这样就完成了父结点到所有子结点的距离求和
然后还需要加上父结点到其他结点的距离和, 注意到这个时候已经求出了根结点的真正的距离和
因为已经求出来了子结点数, 所以某个结点的非子结点数是 n - nodes[i] - 1,
如果将父结点走到子结点改为从根结点出发 dp[child] = dp[root] - nodes[i] + (n - nodes[i])
dp[root] - nodes[i] 表示, 如果从根结点出发到当前结点需要少走 nodes[i] 的距离
n - nodes[i] 表示其他结点走到根结点再走到当前结点需要多走 1 步
时间复杂度为 O(n), 空间复杂度为 O(n)

代码:
C++:

class Solution
{
public:
    vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) 
    {
        vector<vector<int>> graph(n);
        vector<int> dp(n, 0), nodes(n, 1);
        for (const auto& edge : edges) 
        {
            graph[edge.front()].emplace_back(edge.back());
            graph[edge.back()].emplace_back(edge.front());
        }
        post(0, -1, dp, nodes, graph);
        pre(0, -1, dp, nodes, graph, n);
        return dp;
    }
private:
    void post(int root, int parent, vector<int>& dp, vector<int>& nodes, vector<vector<int>>& graph) 
    {
        for (const auto& child : graph[root]) 
        {
            if (child == parent) continue;
            post(child, root, dp, nodes, graph);
            nodes[root] += nodes[child];
            dp[root] += dp[child] + nodes[child];
        }
    }
    
    void pre(int root, int parent, vector<int>& dp, vector<int>& nodes, vector<vector<int>>& graph, int n) {
        for (const auto& child : graph[root]) 
        {
            if (child == parent) continue;
            dp[child] = dp[root] + n - (nodes[child] << 1);
            pre(child, root, dp, nodes, graph, n);
        }
    }
};

Java:

class Solution {
    public int[] sumOfDistancesInTree(int n, int[][] edges) {
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
        int dp[] = new int[n], nodes[] = new int[n];
        Arrays.fill(nodes, 1);
        for (int[] edge : edges) {
            graph.get(edge[0]).add(edge[1]);
            graph.get(edge[1]).add(edge[0]);
        }
        post(0, -1, dp, nodes, graph);
        pre(0, -1, dp, nodes, graph, n);
        return dp;
    }
    
    private void post(int root, int parent, int[] dp, int[] nodes, List<List<Integer>> graph) {
        for (int child : graph.get(root)) {
            if (child == parent) continue;
            post(child, root, dp, nodes, graph);
            nodes[root] += nodes[child];
            dp[root] += dp[child] + nodes[child];
        }
    }
    
    private void pre(int root, int parent, int[] dp, int[] nodes, List<List<Integer>> graph, int n) {
        for (int child : graph.get(root)) {
            if (child == parent) continue;
            dp[child] = dp[root] + n - (nodes[child] << 1);
            pre(child, root, dp, nodes, graph, n);
        }
    }
}

Python:

class Solution:
    def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
        graph, dp, nodes = [list() for _ in range(n)], [0] * n, [1] * n
        for u, v in edges:
            graph[u].append(v)
            graph[v].append(u)
            
        def post(root: int, parent: int) -> None:
            for child in graph[root]:
                if child == parent:
                    continue
                post(child, root)
                nodes[root] += nodes[child]
                dp[root] += dp[child] + nodes[child]
                
        def pre(root: int, parent: int) -> None:
            for child in graph[root]:
                if child == parent:
                    continue
                dp[child] = dp[root] + n - (nodes[child] << 1)
                pre(child, root)
                
        post(0, -1)
        pre(0, -1)
        return dp
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容