Skip to content
LEETFLIX

Sum of Distances in Tree

Solve on LeetCode

Hard · dynamic programming solution for Sum of Distances in Tree. Python, Go, and a step-by-step animation.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 834. Sum of Distances in Tree. The copyrighted prompt is on LeetCode. This page is a working dynamic programming solution for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

n =
5

Output

8

Ways to climb 5 stairs with 1- or 2-steps: Fibonacci, 8.

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Sum of Distances in Tree — dynamic programming

Each answer is a combination of smaller answers already in the table. Built for LeetCode 834. Sum of Distances in Tree.

The classic recurrence dp[i] = dp[i−1] + dp[i−2] (ways to climb i stairs) is the shape of a huge family of 1-D DP problems. Fill left to right; two rolling variables are enough.

Algorithm

  1. Base: a, b = 1, 1 (ways to reach step 0 and 1).
  2. For i from 2 to n, a, b = b, a+b.
  3. Return b.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def sumOfDistancesInTree(self, n: int) -> int:        a, b = 1, 1        for _ in range(2, n + 1):            a, b = b, a + b        return b
Watch this run

03

Interactive walkthrough

Playing “Sum of Distances in Tree — dynamic programming”. Edit the input, hit Run, then scrub.

Approach: Sum of Distances in Tree — dynamic programming

Loading animation…