Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Trees/DP on Trees

Technique

Rerooting DP (all roots)

Compute subtree DP once, then pass 'everything outside this subtree' from parent to child to get the answer for every root in O(n).

Learn firstDP on Trees
0%
mastery
0/7 solved
Practise nextTree Distances II
IdeaPracticePitfalls

Recognise it

The signal

answer for every vertex as the root

  1. 1Brute force

    Run the tree DP from each root: O(n2).

  2. 2The observation

    Recomputing whole-tree DP per root: only the parent-side contribution changes when the root moves one edge.

  3. 3Why it works

    up[v] equals the DP value of the tree outside v's subtree, viewed from v.

Reach for it when

  • +sum of distances from each node
  • +max distance from each node

Not when

  • ×merge operation not invertible and no prefix/suffix trick
  • ×single root suffices

Practice

Next

Tree Distances II

0/7 solved
  • Tree Distances IICSESMedium
  • Tree Distances ICSESMedium
  • Maximum White SubtreeCodeforces1800
  • Tree PaintingCodeforces2100
  • Sum of Distances in TreeHard
  • Tree with Maximum CostCodeforces1900
  • Tree Coin Collecting IICSESHard

Pitfalls

Misconceptions

  • !using subtraction for non-invertible merges like max (needs prefix/suffix maxima)
Go deeper1 combinations · resources

Combinations

  • Rerooting DP (all roots)+DP on Trees

    sum of distances from every node; best value when each node is the root

    Rerooting DP (all roots):
    propagates outside-subtree info to children
    DP on Trees:
    computes answers for subtrees from one root

    Tree Distances IITree Distances ITree Painting

Resources

  • Binary Tree explore cardLeetCode · course
  • Tree cheatsheetTech Interview Handbook · article
  • BST visualizerVisuAlgo · tool
  • Introduction to Tree AlgorithmsUSACO Guide · course
  • Lowest Common Ancestorcp-algorithms · article
  • NeetCode RoadmapNeetCode · sheet
TodayReviewPatternsProblems