码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 834. Sum of Distances in Tree 树中距离之和

时间:2019-09-15 01:12:27      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:dia   xpl   题目   Plan   other   https   class   equal   http   



An undirected, connected?tree with?N?nodes labelled?0...N-1?and?N-1?edges?are?given.

The?ith edge connects nodes?edges[i][0]?and?edges[i][1]?together.

Return a list?ans, where?ans[i]?is the sum of the distances between node?i?and all other nodes.

Example 1:

Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation:
Here is a diagram of the given tree:
  0
 /1   2
   /|  3 4 5
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.



Github 同步地址:

https://github.com/grandyang/leetcode/issues/834



类似题目:
Distribute Coins in Binary Tree



参考资料:

https://leetcode.com/problems/sum-of-distances-in-tree/



LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 834. Sum of Distances in Tree 树中距离之和

标签:dia   xpl   题目   Plan   other   https   class   equal   http   

原文地址:https://www.cnblogs.com/grandyang/p/11520804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!