TExcelTAD
Home › Advanced & Succinct Data Structures › Euler-Tour Trees

Euler-Tour Trees

Dynamic connectivity asks for a graph that changes, with edges inserted and deleted, while answering CONNECTED(u,v)(u, v): is there a path from uu to vv? Union-find (Forests: Union by Rank and Path Compression) solves the incremental case, where edges are only added, in near-constant amortized time. Deletions break it: union-find cannot split a set. The first step towards the fully dynamic problem is the case of a forest: maintain a collection of trees under

  • LINK(u,v)(u, v): add the edge (u,v)(u, v), where uu and vv are in different trees;
  • CUT(u,v)(u, v): remove the tree edge (u,v)(u, v);
  • CONNECTED(u,v)(u, v): are uu and vv in the same tree?

Euler-tour trees (Henzinger and King, 1995; the idea of storing Euler tours in balanced trees goes back to Tarjan's work on dynamic trees) do all three in O(lg⁡n)O(\lg n) time, and they also maintain aggregates over whole trees, such as the number of vertices. They are the building block of the polylogarithmic fully dynamic connectivity algorithm.

Trees as sequences

Walk around a tree starting at any vertex, going down every edge and back up it once. Write down each vertex once (when it is first reached) and each directed edge u→vu \to v when it is traversed. That is an Euler tour of the tree: a sequence of nn vertex entries and 2(n−1)2(n - 1) edge entries, 3n−23n - 2 in total. Think of it as cyclic, since any vertex can be the starting point. The three forest operations become sequence operations:

Forest operation Sequence operation
change the starting vertex to uu (reroot) rotate the cyclic sequence to start at uu: one split and one concatenation
LINK(u,v)(u, v) reroot both tours, then concatenate tour(uu), u→vu \to v, tour(vv), v→uv \to u
CUT(u,v)(u, v) the entries u→vu \to v and v→uv \to u cut the tour into three pieces A,B,CA, B, C: one tree is BB, the other is AA followed by CC
CONNECTED(u,v)(u, v) are the entries of uu and vv in the same sequence?

The program shows these with plain Python lists, which cost O(n)O(n) per operation but make the shapes easy to see.

python · try it yourself
def show(t):
    return " ".join(str(a) if a == b else f"{a}>{b}" for a, b in t)

def reroot(tour, u):                      # rotate the cyclic tour so it starts at vertex u
    i = tour.index((u, u))
    return tour[i:] + tour[:i]

def link(tu, tv, u, v):                   # u's tour, edge u->v, v's tour, edge v->u
    return reroot(tu, u) + [(u, v)] + reroot(tv, v) + [(v, u)]

def cut(tour, u, v):                      # remove both copies of the edge: two tours remain
    i, j = sorted((tour.index((u, v)), tour.index((v, u))))
    return tour[:i] + tour[j + 1:], tour[i + 1:j]

t = {v: [(v, v)] for v in "abcde"}       # five single-vertex trees
t1 = link(t["a"], t["b"], "a", "b")
t2 = link(t1, t["c"], "b", "c")
t3 = link(t["d"], t["e"], "d", "e")
print("a-b-c:     ", show(t2))
print("d-e:       ", show(t3))
t4 = link(t2, t3, "c", "d")
print("link(c, d):", show(t4))
left, right = cut(t4, "a", "b")
print("cut(a, b): ", show(left), "|", show(right))
print("reroot at d:", show(reroot(left, "d")))
a-b-c:      b b>a a a>b b>c c c>b
d-e:        d d>e e e>d
link(c, d): c c>b b b>a a a>b b>c c>d d d>e e e>d d>c
cut(a, b):  c c>b b b>c c>d d d>e e e>d d>c | a
reroot at d: d d>e e e>d d>c c c>b b b>c c>d

Storing each tour in a balanced BST

To make the sequence operations fast, store each tour in a balanced binary search tree keyed by position (an "implicit" key: a node's position is the number of nodes before it in the in-order sequence, computed from subtree sizes). Any balanced BST that supports split at a position and concatenate in O(lg⁡n)O(\lg n) works: red-black trees, splay trees (amortized), or a treap, a BST whose nodes also carry random priorities in heap order, which has expected depth O(lg⁡n)O(\lg n). Each vertex and each directed edge entry is one BST node, and a dictionary maps vertices and edges to their nodes.

  • To find which tour a node is in, walk up parent pointers to the BST root: O(lg⁡n)O(\lg n). CONNECTED compares the roots.
  • To split at a node, first compute its position on the same walk up (adding the sizes of left subtrees passed on the right), then split.

Each forest operation is a constant number of splits, concatenations and walks to the root, so LINK, CUT and CONNECTED take O(lg⁡n)O(\lg n) time: worst case with red-black trees, expected with treaps, amortized with splay trees. With treaps, as in the program below, the bounds are expected.

text
LINK(u, v)                                     CUT(u, v)
1  A = REROOT(u); B = REROOT(v)                1  i, j = positions of (u->v), (v->u), with i < j
2  create entries e1 = (u->v), e2 = (v->u)     2  split the tour into A | e | B | e' | C at i and j
3  CONCAT(A, e1, B, e2)                        3  CONCAT(A, C)        // B is the other tree

REROOT(u)
1  r, i = root and position of u's entry
2  L, R = SPLIT(r, i)
3  return CONCAT(R, L)

The implementation uses a treap with parent pointers. It replays a small example, then runs 4000 random LINK, CUT and CONNECTED operations on 300 vertices and checks every answer against a depth-first search on an explicit forest.

python · try it yourself
import random

rng = random.Random(1995)

class Node:
    __slots__ = ("label", "prio", "left", "right", "parent", "size")
    def __init__(self, label):
        self.label, self.prio = label, rng.random()
        self.left = self.right = self.parent = None
        self.size = 1

def sz(t): return t.size if t else 0

def pull(t):
    t.size = 1 + sz(t.left) + sz(t.right)
    if t.left: t.left.parent = t
    if t.right: t.right.parent = t

def merge(a, b):                       # all of a before all of b
    if not a or not b: return a or b
    if a.prio > b.prio:
        a.right = merge(a.right, b); pull(a); return a
    b.left = merge(a, b.left); pull(b); return b

def split(t, k):                       # first k nodes, the rest
    if not t: return None, None
    t.parent = None
    if sz(t.left) >= k:
        a, b = split(t.left, k)
        t.left = b; pull(t)
        if a: a.parent = None
        return a, t
    a, b = split(t.right, k - sz(t.left) - 1)
    t.right = a; pull(t)
    if b: b.parent = None
    return t, b

def root_and_index(x):                 # walk up: O(depth)
    i = sz(x.left)
    while x.parent:
        p = x.parent
        if x is p.right: i += sz(p.left) + 1
        x = p
    return x, i

class EulerTourForest:
    def __init__(self, n):
        self.vertex = [Node((v, v)) for v in range(n)]      # one occurrence per vertex
        self.edge = {}                                       # (u, v) -> node of the directed edge
    def _reroot(self, u):                                    # rotate u's tour to start at (u, u)
        r, i = root_and_index(self.vertex[u])
        a, b = split(r, i)
        return merge(b, a)
    def connected(self, u, v):
        return root_and_index(self.vertex[u])[0] is root_and_index(self.vertex[v])[0]
    def link(self, u, v):
        assert not self.connected(u, v)
        tu, tv = self._reroot(u), self._reroot(v)
        e1, e2 = Node((u, v)), Node((v, u))
        self.edge[(u, v)], self.edge[(v, u)] = e1, e2
        merge(merge(merge(tu, e1), tv), e2)
    def cut(self, u, v):
        e1, e2 = self.edge.pop((u, v)), self.edge.pop((v, u))
        r, i = root_and_index(e1)
        _, j = root_and_index(e2)
        if i > j: i, j = j, i
        a, rest = split(r, i)              # tour = a, e, b, e', c
        _, rest = split(rest, 1)
        b, rest = split(rest, j - i - 1)
        _, c = split(rest, 1)
        merge(a, c)                         # one tree: a + c; the other: b
    def tree_size(self, u):                 # number of vertices in u's tree, from the tour length
        r, _ = root_and_index(self.vertex[u])
        return (r.size + 2) // 3
    def tour(self, u):
        r, _ = root_and_index(self.vertex[u])
        out = []
        def walk(t):
            if t: walk(t.left); out.append(t.label); walk(t.right)
        walk(r)
        return out

f = EulerTourForest(6)
for u, v in [(0, 1), (1, 2), (1, 3), (4, 5)]:
    f.link(u, v)
show = lambda t: " ".join(str(a) if a == b else f"{a}>{b}" for a, b in t)
print("tour of 0's tree:", show(f.tour(0)))
print("connected(2, 3):", f.connected(2, 3), " connected(0, 4):", f.connected(0, 4), " size(0):", f.tree_size(0))
f.link(3, 4)
print("after link(3, 4): connected(0, 5):", f.connected(0, 5), " size(0):", f.tree_size(0))
f.cut(1, 3)
print("after cut(1, 3): connected(0, 5):", f.connected(0, 5), " sizes:", f.tree_size(0), f.tree_size(5))
print("tour of 5's tree:", show(f.tour(5)))

# Stress test against DFS on an explicit forest; record the deepest walk to a treap root.
def depth(x):
    d = 0
    while x.parent: x, d = x.parent, d + 1
    return d

n = 300
g, edges, adj = EulerTourForest(n), [], [set() for _ in range(n)]
def dfs_connected(u, v):
    seen, stack = {u}, [u]
    while stack:
        x = stack.pop()
        for y in adj[x]:
            if y not in seen: seen.add(y); stack.append(y)
    return v in seen
worst = 0
for step in range(4000):
    u, v = rng.randrange(n), rng.randrange(n)
    r = rng.random()
    if r < 0.45 and u != v and not g.connected(u, v):
        g.link(u, v); edges.append((u, v)); adj[u].add(v); adj[v].add(u)
    elif r < 0.7 and edges:
        a, b = edges.pop(rng.randrange(len(edges)))
        g.cut(a, b); adj[a].discard(b); adj[b].discard(a)
    else:
        assert g.connected(u, v) == dfs_connected(u, v)
    worst = max(worst, depth(g.vertex[u]), depth(g.vertex[v]))
print(f"4000 random operations on {n} vertices agree with DFS; {len(edges)} edges at the end")
print(f"deepest treap node seen: depth {worst} (tours have at most {3 * n - 2} nodes, lg = {(3 * n - 2).bit_length() - 1})")
tour of 0's tree: 1 1>0 0 0>1 1>2 2 2>1 1>3 3 3>1
connected(2, 3): True  connected(0, 4): False  size(0): 4
after link(3, 4): connected(0, 5): True  size(0): 6
after cut(1, 3): connected(0, 5): False  sizes: 3 3
tour of 5's tree: 3 3>4 4 4>5 5 5>4 4>3
4000 random operations on 300 vertices agree with DFS; 214 edges at the end
deepest treap node seen: depth 23 (tours have at most 898 nodes, lg = 9)

The deepest node stays at a small multiple of lg⁡(3n)\lg(3n), as expected for a treap.

In C++

The same structure with raw pointers and std::mt19937 priorities. It builds two paths, links them, cuts two edges and reports tree sizes, which come from the tour length 3n−23n - 2 stored in the BST root.

cpp · try it yourself
#include <cstdio>
#include <map>
#include <random>
#include <utility>
#include <vector>

// Euler-tour forest: each tour is an implicit treap (keys = positions) with parent pointers.
struct Node {
    int a, b;                       // a == b: the vertex a; otherwise the directed edge a -> b
    unsigned prio;
    Node *l = nullptr, *r = nullptr, *p = nullptr;
    int size = 1;
};

std::mt19937 rng(1995);
int sz(Node* t) { return t ? t->size : 0; }
void pull(Node* t) {
    t->size = 1 + sz(t->l) + sz(t->r);
    if (t->l) t->l->p = t;
    if (t->r) t->r->p = t;
}
Node* merge(Node* a, Node* b) {
    if (!a || !b) return a ? a : b;
    if (a->prio > b->prio) { a->r = merge(a->r, b); pull(a); return a; }
    b->l = merge(a, b->l); pull(b); return b;
}
std::pair<Node*, Node*> split(Node* t, int k) {          // first k nodes, rest
    if (!t) return {nullptr, nullptr};
    t->p = nullptr;
    if (sz(t->l) >= k) {
        auto [a, b] = split(t->l, k);
        t->l = b; pull(t);
        if (a) a->p = nullptr;
        return {a, t};
    }
    auto [a, b] = split(t->r, k - sz(t->l) - 1);
    t->r = a; pull(t);
    if (b) b->p = nullptr;
    return {t, b};
}
std::pair<Node*, int> root_index(Node* x) {
    int i = sz(x->l);
    for (; x->p; x = x->p)
        if (x == x->p->r) i += sz(x->p->l) + 1;
    return {x, i};
}

class EulerTourForest {
    std::vector<Node> vertex;
    std::map<std::pair<int, int>, Node*> edge;
    std::vector<Node*> pool;
    Node* make(int a, int b) { auto* x = new Node{a, b, static_cast<unsigned>(rng())}; pool.push_back(x); return x; }
    Node* reroot(int u) {
        auto [r, i] = root_index(&vertex[u]);
        auto [a, b] = split(r, i);
        return merge(b, a);
    }
public:
    explicit EulerTourForest(int n) : vertex(n) {
        for (int v = 0; v < n; ++v) vertex[v] = Node{v, v, static_cast<unsigned>(rng())};
    }
    ~EulerTourForest() { for (auto* x : pool) delete x; }
    bool connected(int u, int v) { return root_index(&vertex[u]).first == root_index(&vertex[v]).first; }
    int tree_size(int u) { return (root_index(&vertex[u]).first->size + 2) / 3; }
    void link(int u, int v) {
        Node* tu = reroot(u);
        Node* tv = reroot(v);
        Node* e1 = make(u, v);
        Node* e2 = make(v, u);
        edge[{u, v}] = e1; edge[{v, u}] = e2;
        merge(merge(merge(tu, e1), tv), e2);
    }
    void cut(int u, int v) {
        Node* e1 = edge.at({u, v});
        Node* e2 = edge.at({v, u});
        edge.erase({u, v}); edge.erase({v, u});
        auto [r, i] = root_index(e1);
        int j = root_index(e2).second;
        if (i > j) std::swap(i, j);
        auto [a, rest1] = split(r, i);
        auto [e, rest2] = split(rest1, 1);
        auto [b, rest3] = split(rest2, j - i - 1);
        auto [e_, c] = split(rest3, 1);
        (void)e; (void)e_; (void)b;
        merge(a, c);
    }
};

int main() {
    EulerTourForest f(8);
    for (auto [u, v] : std::vector<std::pair<int, int>>{{0, 1}, {1, 2}, {2, 3}, {4, 5}, {5, 6}, {6, 7}}) f.link(u, v);
    std::printf("connected(0, 3) = %d, connected(3, 4) = %d\n", f.connected(0, 3), f.connected(3, 4));
    f.link(3, 4);
    std::printf("after link(3, 4): connected(0, 7) = %d, size = %d\n", f.connected(0, 7), f.tree_size(0));
    f.cut(1, 2);
    f.cut(5, 6);
    std::printf("after cut(1, 2), cut(5, 6): sizes %d %d %d\n", f.tree_size(0), f.tree_size(2), f.tree_size(7));
    std::printf("connected(2, 5) = %d, connected(0, 7) = %d\n", f.connected(2, 5), f.connected(0, 7));
}
connected(0, 3) = 1, connected(3, 4) = 0
after link(3, 4): connected(0, 7) = 1, size = 8
after cut(1, 2), cut(5, 6): sizes 2 4 2
connected(2, 5) = 1, connected(0, 7) = 0

Aggregates over a tree

Because every vertex of a tree appears in its tour exactly once, any value that can be maintained in BST nodes, such as a count, a sum of vertex weights or a flag "some vertex in this subtree is marked", is available for the whole tree at the root of its BST, in O(1)O(1) after the O(lg⁡n)O(\lg n) walk up. The program's tree_size is the simplest instance. The fully dynamic connectivity algorithm relies on exactly this: it marks vertices that have certain non-tree edges and asks "find any marked vertex in this tree" by descending from the root along marked subtrees, O(lg⁡n)O(\lg n) per vertex found.

What Euler-tour trees cannot do easily is answer questions about paths, such as "the maximum edge weight on the path from uu to vv": a path is not a contiguous piece of the tour. That is what link-cut trees are for.

Structure LINK, CUT, CONNECTED Subtree aggregates Path aggregates
Euler-tour tree (balanced BST) O(lg⁡n)O(\lg n) worst case yes, whole trees and subtrees (with rooting) no
link-cut tree (splay trees) O(lg⁡n)O(\lg n) amortized only with extensions yes

Test yourself

How many entries does the Euler tour of a tree with nn vertices have in this representation?

  1. nn
  2. 2n−22n - 2
  3. 3n−23n - 2
  4. n2n^2

After CUT(u,v)(u, v) splits the tour into A,u→v,B,v→u,CA, u \to v, B, v \to u, C, which pieces form the two new trees?

  1. AA and BCB C
  2. BB and ACA C
  3. ABA B and CC
  4. AA, BB and CC are three trees

Why are Euler-tour trees not suited to queries like "the heaviest edge on the path from uu to vv"?

  1. They do not store edges
  2. A tree path is generally not a contiguous segment of the Euler tour, so a BST range aggregate does not give it
  3. They are too slow for paths
  4. Paths change after rerooting