Data Structures19 sections · 729 units
Open in Course

Euler Tour Technique

Flattening subtrees

The Euler tour technique converts subtree queries to range queries. Perform a DFS and record each node when you enter and exit.

A node vv's subtree corresponds to a contiguous range in this tour. Store tin[v]tin[v] (entry time) and tout[v]tout[v] (exit time).

The subtree of vv contains exactly nodes with entry times in [tin[v],tout[v]][tin[v], tout[v]]. Now subtree sum, subtree min, and similar queries become range queries on an array.

Use a segment tree or Fenwick tree on the tour. Time: O(logn)O(\log n). Space: O(n)O(n).