834. Sum of Distances in Tree Hard

@problem@discussion
#Dynamic Programming#Tree#Depth-First Search#Graph



1/**
2 * [834] Sum of Distances in Tree
3 *
4 * There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
5 * 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.
6 * Return an array answer of length n where answer[i] is the sum of the distances between the i^th node in the tree and all other nodes.
7 *  
8 * Example 1:
9 * <img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist1.jpg" style="width: 304px; height: 224px;" />
10 * Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
11 * Output: [8,12,6,10,10,10]
12 * Explanation: The tree is shown above.
13 * We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
14 * equals 1 + 1 + 2 + 2 + 2 = 8.
15 * Hence, answer[0] = 8, and so on.
16 * 
17 * Example 2:
18 * <img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist2.jpg" style="width: 64px; height: 65px;" />
19 * Input: n = 1, edges = []
20 * Output: [0]
21 * 
22 * Example 3:
23 * <img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist3.jpg" style="width: 144px; height: 145px;" />
24 * Input: n = 2, edges = [[1,0]]
25 * Output: [1,1]
26 * 
27 *  
28 * Constraints:
29 * 
30 * 	1 <= n <= 3 * 10^4
31 * 	edges.length == n - 1
32 * 	edges[i].length == 2
33 * 	0 <= ai, bi < n
34 * 	ai != bi
35 * 	The given input represents a valid tree.
36 * 
37 */
38pub struct Solution {}
39
40// problem: https://leetcode.com/problems/sum-of-distances-in-tree/
41// discuss: https://leetcode.com/problems/sum-of-distances-in-tree/discuss/?currentPage=1&orderBy=most_votes&query=
42
43// submission codes start here
44
45impl Solution {
46    pub fn sum_of_distances_in_tree(n: i32, edges: Vec<Vec<i32>>) -> Vec<i32> {
47        vec![]
48    }
49}
50
51// submission codes end
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test_834() {
59    }
60}
61


Back
© 2025 bowen.ge All Rights Reserved.