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

Small-to-Large Merging (DSU on tree)

When merging sets, always insert the smaller into the larger; each element moves O(log n) times, giving O(n log n) (times the set cost).

Learn firstTree DFS (Paths & Recursion)Hash Map / Hash Set Lookup
0%
mastery
0/6 solved
Practise nextCount Paths
IdeaPracticePitfalls

Recognise it

The signal

per-subtree distinct counts / dominating colours

  1. 1Brute force

    Build each subtree's set from scratch: O(n2).

  2. 2The observation

    Repeated copying: an element that moves at least doubles its set size.

  3. 3Why it works

    Each element is copied only when its set size at least doubles.

Reach for it when

  • +merge maps of children
  • +union-find with explicit member lists

Not when

  • ×queries need order statistics per subtree beyond what a set gives
  • ×offline Euler tour + BIT can be simpler for distinct counts

Practice

Next

Count Paths

0/6 solved
  • Count PathsCodeforces2000
  • Tree RequestsCodeforces2200
  • Distinct ColorsCSESHard
  • Lomsat gelralCodeforces2300
  • Dominant IndicesCodeforces2300
  • XOR TreeCodeforces2400

Pitfalls

Misconceptions

  • !swapping containers by copy instead of by pointer/move (loses the bound)
  • !Two different methods share the cue: sack / DSU on tree keeps the heavy child's data and re-adds light subtrees (O(n log n), O(1) adds); merging std::sets small into large is O(n log^2 n).
Go deeper1 combinations · resources

Combinations

  • Small-to-Large Merging (DSU on tree)+Tree DFS (Paths & Recursion)

    distinct colours per subtree; dominant colour sums

    Small-to-Large Merging (DSU on tree):
    merges child sets keeping the largest
    Tree DFS (Paths & Recursion):
    post-order over subtrees

    Distinct ColorsLomsat gelralTree Requests

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