Start with a global timer at . Run DFS from the root. When entering node , set tin[v] = timer and increment. Recurse on children. When exiting, set tout[v] = timer without incrementing. Pseudocode:
timer := 0
function dfs(v, parent):
tin[v] := timer
timer := timer + 1
for each child u of v:
if u != parent then
dfs(u, v)
tout[v] := timer
After this DFS, you have entry and exit times for every node. All values are unique ( to ), while values may repeat. All values stay within . This is part of the Euler Tour framework for converting tree structures into arrays.
This runs in time and uses space.