🐐
LeetGoat
Interview Prep
Competitive Programming
Discord
Tree helper templates
Range queries
2D range queries
Sets
Union find
Strings
Tree queries
Tree helpers
Graphs
Matrices
Math
Primes
Bit ops & Bitset
Geometry
Misc.
Golden References
Edge lists
Edge list to rooted tree O(n)
Roots an [a, b] edge list at any node you pass and returns children lists, sized to the largest label (0..n-1 or 1..n)
Weighted edge list to rooted tree O(n)
Edges come as [a, b, w], rooted at any node you pass; returns children[node] = [(child, weight), ...], sized to the largest label
Centroid
Find centroids O(n)
The 1 or 2 centroids of an unrooted [a, b] edge list, sorted. Removing one leaves every piece at most n/2. Labels 0..n-1 or 1..n; needs at least one edge
Centroid decomposition O(n log n)
Splits an unrooted [a, b] edge list at centroids, recursively; returns every piece as (its centroid, children map of that piece rooted at the centroid)
Reroot DP
Farthest node from every node O(n)
For every node, the farthest other node and its distance (ties go to the smallest id). Labels 0..n-1 or 1..n, detected automatically
Weighted
Sum of distances to all nodes O(n)
For every node, the sum of its distances to all other nodes. Labels 0..n-1 or 1..n, detected automatically
Weighted
Hashing
All subtree hashes O(n log n)
A random 64-bit hash of every node's subtree: two nodes match exactly when their subtrees are the same shape (rooted, children unordered)
Tree Helper Templates — LeetGoat