learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Algorithm Selection

Select an algorithm and generate steps to begin visualization

Heavy-Light Decomposition Visualizer

Any tree path in O(log n) array intervals

Splits a rooted tree into chains along each vertex's largest subtree, so any path crosses O(log n) chains, each one an interval of an array for a segment tree

Time: O(n) to build, O(log² n) per path query
Space: O(n)
Use Case: Path sums and maxima on trees with updates, routing trees in networks, competitive programming
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Heavy-Light Decomposition

Heavy-light decomposition cuts a rooted tree into vertical chains so that any path in the tree crosses only O(log n) of them. Each vertex picks as its heavy child the child with the largest subtree, and the edge to it is heavy, the other edges are light. Heavy edges join into chains. The key fact is short: a light child has at most half of its parent's subtree, otherwise it would be the largest, so walking down a light edge at least halves the subtree size, and that can happen at most log2 n times on any path. Sleator and Tarjan used the idea in 1983 for link-cut trees, and today it is the standard way to run array data structures, such as segment trees, over paths of a tree.

How it works

Two passes do the decomposition. The first computes every subtree size from the leaves up, and each vertex marks its heavy child. The second is a depth-first search that visits the heavy child first, so every chain gets consecutive positions in an array, and each light child starts a new chain as its head. A path query between u and v then moves the vertex whose chain head is deeper up to the head's parent, taking its piece of chain as one array interval, until both lie on the same chain, and the last interval finishes the path. The visualizer colours each chain, writes subtree sizes and positions in badges and lights up each interval of the path. In the 15-vertex example, the path from J to O becomes 4 intervals, E..J, G..O, C and A..B, crossing 3 light edges, and the two sides meet at the root A.

Applications

With a segment tree over the array, heavy-light decomposition answers path sums, path maxima and path updates on a tree in O(log² n) per operation, and subtree queries in O(log n), because a subtree is one interval too. That covers a wide family of problems: the maximum edge weight between two vertices, which the second-best spanning tree needs, the total load on a route through a hierarchy, or changing all weights along a path. Network and file system trees, routing trees and organisation charts all fit. The same light edge argument bounds link-cut trees, used in dynamic tree algorithms and fast maximum flow, and the method is one of the most common advanced tools in competitive programming.

Pseudocode

Two passes build the chains, then a path query climbs chain by chain.

Decompose(root):
    size(v) = 1 + sum of size(c) over the children c of v   // post-order
    heavy(v) = the child of v with the largest size
    pos = 0
    DFS(v, head):
        head(v) = head, position(v) = pos, pos = pos + 1
        if v has a heavy child: DFS(heavy(v), head)        // same chain
        for each other child c: DFS(c, c)                  // new chain
    DFS(root, root)

PathQuery(u, v):
    while head(u) != head(v):
        if depth(head(u)) < depth(head(v)): swap u and v
        use the interval [position(head(u)), position(u)]
        u = parent(head(u))
    use the interval between position(u) and position(v)  // same chain

Going down a light edge at least halves the subtree size, so a path from the root has at most log2 n light edges and touches at most log2 n + 1 chains. A path between u and v is two such climbs, so a query uses O(log n) intervals, each answered by a segment tree in O(log n).

Worked example, step by step

The 15-vertex tree loaded on this page, rooted at A, with the query J to O.

Example graph: Edges A–B, A–C, B–D, B–E, C–F, C–G, D–H, D–I, E–J, F–K, F–L, G–O, H–N and K–M.

  1. Subtree sizes. A 15, B 7, C 7, D 4, F 4, E 2, G 2, H 2, K 2, and 1 for the six leaves. B and C tie at 7, and the first one, B, becomes heavy.
  2. Heavy children. A picks B, B picks D, D picks H, H picks N. C picks F, F picks K, K picks M. E and G have one child each, J and O, which are heavy.
  3. Chains and positions. A–B–D–H–N takes positions 0 to 4, then I 5, E–J 6 and 7, C–F–K–M 8 to 11, L 12 and G–O 13 and 14. Six chains in all.
  4. Query J to O. J and O lie on different chains. The query takes E..J (6 to 7) and climbs to B, then G..O (13 to 14) and climbs to C, then C alone (8) and climbs to A.
  5. Last interval. B and A share the first chain, so A..B (0 to 1) finishes the path. The sides meet at A, the lowest common ancestor of J and O.

4 intervals, [6, 7], [13, 14], [8, 8] and [0, 1], with 3 light edges crossed, within the bound of about 2·log2 15 ≈ 7.8.

Complexity, and where it comes from

Time: O(n) to build, O(log² n) per path query with a segment tree · Space: O(n)

Both passes visit every vertex once, so building is O(n). A path crosses O(log n) light edges, so a query splits into O(log n) intervals, and a segment tree answers each in O(log n), for O(log² n) per path query or update. A subtree is one interval [position(v), position(v) + size(v) − 1], so subtree queries cost O(log n).

When to use Heavy-Light Decomposition, and when not to

Other tools for questions about tree paths.

AlternativePrefer it whenCost
Binary liftingOnly static path aggregates such as the maximum are needed, with no updates.O(n log n) to build, O(log n) per query
Euler tour and a segment treeQueries and updates concern subtrees rather than paths. Each subtree is one interval.O(log n) per query
Link-cut treesThe tree itself changes, with edges cut and linked between queries.O(log n) amortized per operation

Common pitfalls

  • Choosing the heavy child by height. The heavy child must have the largest subtree, not the deepest one. Choosing by height can leave many light edges on a path and lose the logarithmic bound.
  • Moving the wrong vertex. At each step move the vertex whose chain head is deeper. Moving the vertex that is deeper itself can climb past the lowest common ancestor and count part of the path twice.
  • Mixing up edge and vertex values. When values sit on edges, store each edge at its lower vertex and leave out the lowest common ancestor's position in the last interval. Otherwise the edge above it is counted though it is not on the path.

Frequently asked questions

Why at most log2 n light edges?
A light child has a subtree of at most half its parent's, because the heavy child is at least as large. Starting from n vertices, halving can happen at most log2 n times before reaching 1.
Does it also give the lowest common ancestor?
Yes. When u and v end on the same chain, the higher of the two is their lowest common ancestor. Here the query J to O ends on the first chain with B and A, so the answer is A.
When is it worth the code?
When a tree carries values on its vertices or edges that change between path queries, such as loads in a network or costs in a hierarchy. For a static tree, binary lifting is simpler.

Related algorithms: Lowest Common Ancestor (Binary Lifting), Tree Traversal (Pre, In, Post, Level), Tree Diameter and Center, Second-Best Minimum Spanning Tree, Depth-First Search

Built by Mohammed Islam HadjoudjWork with me

An example graph: you can change it, or start blank.

Zoom Controls

30%
Nodes: 15
Edges: 14