progress

~/problems / Tree techniques / Euler tour of a tree

Entry and exit times

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

An Euler tour flattens a tree so every subtree is a contiguous range. DFS from the root with a timer starting at 0:

  • on first entering v: tin[v] = timer, then add one to timer;
  • after all of v's children: tout[v] = timer.

The subtree of v is then the nodes u with tin[v] <= tin[u] < tout[v].

Implement euler_tour(n, edges, root) -> tuple[list[int], list[int]] returning (tin, tout) for nodes 0 .. n-1 and n - 1 undirected edges. Any child order is accepted.

#       0
#      / \
#     1   2
#         |
#         3
euler_tour(4, [(0, 1), (0, 2), (2, 3)], 0)
# ([0, 1, 2, 3], [4, 2, 4, 4])    visiting child 1 before child 2
# ([0, 3, 1, 2], [4, 4, 3, 3])    visiting child 2 before child 1 is also fine

![The four-node tree with each node marked [tin, tout): 0 is [0, 4), 1 is [1, 2), 2 is [2, 4), 3 is 3, 4). Listing nodes in entry order gives 0, 1, 2, 3, and the subtree of node 2, nodes 2 and 3, is the contiguous slice from 2 up to 4.

1 <= n <= 10^5.

⭐ Bonus: a speed test on a 100,000-node path earns a star. Recursion hits Python's recursion limit there, so use an explicit stack.

Show hint

push (node, parent, exiting) entries: on entering, record tin, push the exit marker, then the children; on exiting, record tout.

Topic: Euler tour of a tree. Flatten subtrees into contiguous ranges with tin/tout.

0:00
Ctrl ' run · Ctrl ↵ submit
esc