Rerooting Technique

You know tree DP for one root. Learn to compute answers for all roots in linear time.

39 lessons
114 min

Lessons

1. Intro

(Why rerooting matters)

3m

2. The Single-Root Problem (Why you need rerooting)

(The $O(n^2)$ problem)

3m

3. Rerooting Intuition (Reusing previous work)

(Incremental updates)

3m

4. The Two-Pass Algorithm (Down and up)

(The core algorithm)

3m

5. Down Pass (Computing subtree answers)

(Subtree DP)

3m

6. Up Pass (Propagating parent contributions)

(Parent contributions)

3m

7. Combining Down and Up (Final answers)

(Merging results)

3m

8. Contribution (What each subtree gives)

(Child contribution logic)

3m

9. Prefix-Suffix Arrays (Excluding one child)

(Efficient sibling exclusion)

3m

10. Rerooting Template (General pattern)

(Apply to any problem)

3m

11. Problem - Tree Distances II (CSES 1133)

(CSES problem)

3m1 problems

12. Core Observation (Moving root changes distances)

(Distance shift insight)

3m

13. Down Pass (Subtree distances)

(Subtree sums)

3m

14. Up Pass (Parent contribution)

(Outside contributions)

3m

15. Final Answer (Combining down and up)

(Merge down and up)

3m

16. Tree Distances II - Implementation (Two DFS passes)

(C++ code)

3m1 problems

17. Walkthrough (Small tree example)

(4-node tree)

3m

18. Lessons Learned (Sum aggregation)

(Distance aggregation)

3m

19. Problem - Sum of Distances in Tree (LeetCode 834)

(LeetCode variant)

3m1 problems

20. Implementation Notes (Array indexing)

(0-indexed implementation)

3m1 problems

21. Complexity Analysis (Linear time)

O(n) proof

3m

22. Rerooting vs Brute Force (Why rerooting wins)

($n$ times faster)

3m

23. When to Use Rerooting (Problem patterns)

(All-roots signal)

3m

24. State Design (What to track)

(DP state choice)

3m

25. Handling Multiple Children (Prefix-suffix pattern)

(Sibling combination)

3m

26. Rerooting with Max (Not just sum)

(Maximum problems)

3m

27. Rerooting with Count (Combinatorial problems)

(Distance histograms)

3m

28. Edge Cases (Small trees)

(n=1 and n=2)

3m

29. Debugging Rerooting (Common mistakes)

(Double-counting)

3m

30. Rerooting Variations (Different problems)

(3-pass extensions)

3m

31. Practice Tips (Getting comfortable)

(Solve 5 problems)

3m

32. Quiz: Rerooting Answer

Knowledge check

2m1 problems

33. Quiz: Rerooting Up Value

Knowledge check

2m1 problems

34. Quiz: Rerooting Selection

Knowledge check

2m1 problems

35. Common Mistakes (What to avoid)

(Exclude child correctly)

3m

36. Rerooting in Contests (Recognition)

(For each node signal)

3m

37. Advanced Rerooting (Multiple states)

(Tuple states)

3m

38. Rerooting with Updates (Dynamic trees)

(Rare dynamic case)

3m

39. Section Recap

(Two-pass proficiency)

3m

Practice Problems

Ready to start learning?

Access all 39 lessons with interactive content and progress tracking.