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/Tree DFS (Paths & Recursion)

Pattern

DP on Trees

dp[v][state] computed from children's dp values in post-order (e.g. take/skip v, cover state, matched or not).

Learn firstTree DFS (Paths & Recursion)1D / Fibonacci-styleUnlocksVirtual (Auxiliary) Tree
0%
mastery
0/19 solved
Practise nextKingdom and its Cities
IdeaPracticePitfalls

Recognise it

The signal

choose a set of nodes on a tree with adjacency constraints

  1. 1Brute force

    Enumerate subsets of nodes.

  2. 2The observation

    Exponential subsets: each subtree's answer depends only on its root's state.

  3. 3Why it works

    dp[v][s] is optimal for v's subtree given v is in state s.

Reach for it when

  • +cameras/guards/matching on tree
  • +count/optimise over subtrees

Not when

  • ×answer needed for every root (rerooting)
  • ×path queries (binary-lifting / hld)

Practice

Next

Kingdom and its Cities

0/19 solved
  • White-Black Balanced SubtreesCodeforces1300
  • Tree Distances IICSESMedium
  • Tree Distances ICSESMedium
  • Maximum White SubtreeCodeforces1800
  • House Robber IIIMedium
  • Tree MatchingCSESMedium
  • Kingdom and its CitiesCodeforces2800
  • Count PathsCodeforces2000
  • Karen and SupermarketCodeforces2400
  • Berland FederalizationCodeforces2200
  • Tree PaintingCodeforces2100
  • Sum of Distances in TreeHard

Pitfalls

Misconceptions

  • !greedy on trees often fails where DP works (e.g. house robber III)
Go deepervariants and techniques · 3 combinations · resources

Variants and techniques

  • 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).

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

  • Virtual (Auxiliary) Tree+DP on Trees+Binary Lifting & LCA

    many queries with a small vertex set each and sum of k bounded

    Virtual (Auxiliary) Tree:
    shrink the tree to the O(k) marked vertices and their LCAs
    DP on Trees:
    run the separation/cover DP on the small tree
    Binary Lifting & LCA:
    LCA queries while building the virtual tree

    Kingdom and its CitiesCount Paths

  • DP on Trees+Combinatorics mod p (nCr, Catalan, stars and bars)

    count the orders in which tree nodes can be added parent-first (or BST insert orders)

    DP on Trees:
    subtree sizes and the ways for each child
    Combinatorics mod p (nCr, Catalan, stars and bars):
    interleave the children's orders with multinomials, i.e. n! / product of subtree sizes

    Count Ways to Build Rooms in an Ant ColonyNumber of Ways to Reorder Array to Get Same BST

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