834. Sum of Distances in Tree
https://leetcode.com/problems/sum-of-distances-in-tree/
Previous114. Flatten Binary Tree to Linked ListNext1443. Minimum Time to Collect All Apples in a Tree
Last updated
Was this helpful?
https://leetcode.com/problems/sum-of-distances-in-tree/
Last updated
Was this helpful?
问给定树上每个结点到其它任意结点的距离和。虽然不是二叉树,但依然可以分治看,只是不是看左右结点,而是任意结点x都可以看作它和它的parent y把树分成了两边。让x@x代表x到它下面所有结点距离和,#x表x和它下面所有结点的个数,那么可以得出:
res[x] = x@x + y@y + #y res[y] = y@y + x@x + #x res[x] = res[y] + #y - #x = res[y] + (N - #x) - #x
而res[root]求解是很简单的,一次后序遍历即可。那用上面的关系再做一次先序遍历就可以依次得到res[root->children] => res[root->children->children]...
思路参考了。