C · Grandmaster · 12 min

Euler Tour of a Tree

Flatten the tree: in[v] is the first visit, out[v] the last. Subtree of v is the contiguous segment [in[v], out[v]). Range structures now speak subtree.

Subtree queries ('sum of values in v's subtree', CSES Subtree Queries) look like they need tree walks per query. After an Euler tour, the subtree is an array interval, and a Fenwick or segment tree does the rest.

DFS: stamp in[v] = timer++ on enter, recurse children, stamp out[v] = timer (half-open) or out[v] = timer++ (closed, two arrays). Path queries need a different flattening (in on enter, out on exit as a second slot, difference Fenwick) — CSES Path Queries.

This is USACO Gold 'Euler Tour Technique (optional)' and it is not optional the first time you see subtree + update.

in/out timestamps, subtree size = out-injs
function eulerTour(n, adj, root = 0) {
  const inn = Array(n).fill(0);
  const out = Array(n).fill(0);
  let timer = 0;
  function dfs(v, p) {
    inn[v] = timer++;
    for (const u of adj[v]) if (u !== p) dfs(u, v);
    out[v] = timer;
  }
  dfs(root, -1);
  return { inn, out };
}

// subtree of v is indices [inn[v], out[v]) in tour order
// size[v] = out[v] - inn[v]

TRACE

Root 0, children 1 and 2; 2 has child 3. Tour order.

enter 0

in[0]=0. timer=1.

1 / 4

CHECK

Point add on node x, subtree sum of v. After the tour, the operations are…

CHECK

Is u in v's subtree?

Checks 0/2

Next lesson