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)

Technique

Centroid Decomposition

Recursively remove a centroid (largest remaining part <= n/2) so every path passes through some centroid at one of O(log n) levels.

Learn firstTree DFS (Paths & Recursion)Divide and Conquer (merge-sort counting)
0%
mastery
0/4 solved
Practise nextFixed-Length Paths I
IdeaPracticePitfalls

Recognise it

The signal

count/optimise over ALL paths in a tree (length k, weight bound)

  1. 1Brute force

    All pairs of nodes O(n2).

  2. 2The observation

    Pair enumeration: each path is handled at the unique highest centroid on it.

  3. 3Why it works

    The centroid tree has depth O(log n) and each path is counted at its top centroid.

Reach for it when

  • +nearest marked node queries with updates

Not when

  • ×path queries between given endpoints (binary-lifting/hld simpler)
  • ×dynamic tree structure

Practice

Next

Fixed-Length Paths I

0/4 solved
  • Fixed-Length Paths ICSESHard
  • Fixed-Length Paths IICSESHard
  • Xenia and TreeCodeforces2400
  • Finding a CentroidCSESHard

Pitfalls

Misconceptions

  • !double counting paths that stay in one child subtree
Go deeper1 combinations · resources

Combinations

  • Centroid Decomposition+Graph BFS / DFS

    count paths of length k; nearest marked vertex queries

    Centroid Decomposition:
    splits paths by their top centroid
    Graph BFS / DFS:
    BFS/DFS collects depths from each centroid

    Fixed-Length Paths IFixed-Length Paths IIXenia and Tree

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