Trees are everywhere in computer science — file systems, parse trees, organisational charts, phylogenetic hierarchies. Algorithms on trees are generally easy when they work top-down: just recurse. But the moment someone asks "what is the sum of all values in this subtree?" or, worse, "now update that node's value — and answer the same query again", the naïve O(n) scan over the subtree stops being acceptable.
The Euler tour technique is a beautiful 1984 trick by Robert Tarjan and Uzi Vishkin that sidesteps the difficulty entirely. Walk the tree with a depth-first search and record, for every node, the moment you first visit it (its in-time) and the moment you leave it for the last time (its out-time). Write those times into an array as you go.
The magic: every subtree rooted at node occupies exactly the contiguous range in that flat array. A subtree query becomes a range query on a sequence — and range queries are a solved problem, answerable in with a segment tree or a Fenwick tree. Suddenly the entire toolkit of 1-D data structures is available for tree problems.
This article explores the technique, lets you build the tour interactively, and explains how it extends to fully dynamic trees where edges are inserted or deleted on the fly.
Comments
Loading comments...