Skip to content

12.1 Write a depth-first search without recursion

You write a depth-first search of your own, with hooks that are called when a node is entered and when it is left.

You want to go through a graph and compute something on the way. Many such computations can be written as a depth-first search with some code of your own. Written recursively, they overflow the call stack on deep graphs, such as a long chain of calls or a deeply nested syntax tree. You need this for:

  • a value of each node computed from the values of its out-nodes, such as the sizes of subtrees or costs;
  • the nodes in the order in which the search finishes them, such as each method after the methods it calls, if the calls have no cycle;
  • a search that stops at the first node that matches.

The example graph family models a family tree with one parent per person, over four generations. It has an edge from each parent to each child. Ada is the root, and her children are Ben and Cleo. How many descendants does each person have? These are the person’s children, grandchildren and so on, without the person. The picture after shows the counts in brackets:

The family tree
The number of descendants of each person
0: Ada1: Ben2: Cleo3: Dora4: Emil5: Finn6: Greta7: Hugo8: Ida9: Jonas
0: Ada (9)1: Ben (4)2: Cleo (3)3: Dora (2)4: Emil (0)5: Finn (2)6: Greta (0)7: Hugo (0)8: Ida (0)9: Jonas (0)
Input
  • Start node
Output
  • Person with the number of descendants

leaveNodeleave_nodeleaveNodeLeaveNode is called after the search has finished the subtree of a node, so the counts of its children are ready:

// graph, a field of DfsTraverser, is the graph it searches.
class Descendants extends DfsTraverser {
final int[] count;
Descendants(Graph family) {
super(family);
count = new int[family.nodeCount()];
}
@Override
protected boolean enterNode(int person) {
return true; // search from the children of every person
}
@Override
protected void leaveNode(int person) {
// Called after the whole subtree of the person: the counts of the children are
// complete.
for (int child : graph.outNodes(person)) {
count[person] += 1 + count[child];
}
}
}
var descendants = new Descendants(family);
descendants.run(ada);
// descendants.count: [9, 4, 3, 2, 0, 2, 0, 0, 0, 0] - Ada has 9, Ben 4, Cleo 3, ...
Full example
// The hooks are a type of your own; each receives a DfsControl, whose graph() is the
// graph the DfsTraverser searches.
struct Descendants {
count: Vec<u32>,
}
impl DfsHooks for Descendants {
fn enter_node(&mut self, _person: u32, _control: &mut DfsControl<'_>) -> bool {
true // search from the children of every person
}
fn leave_node(&mut self, person: u32, control: &mut DfsControl<'_>) {
// Called after the whole subtree of the person: the counts of the children
// are complete.
for &child in control.graph().out_nodes(person).iter() {
self.count[person as usize] += 1 + self.count[child as usize];
}
}
}
let mut descendants = Descendants {
count: vec![0; family.node_count() as usize],
};
DfsTraverser::new(&family).run_from(ada, &mut descendants);
// descendants.count: [9, 4, 3, 2, 0, 2, 0, 0, 0, 0] - Ada has 9, Ben 4, Cleo 3, ...
Full example
// this.graph, a field of DfsTraverser, is the graph it searches.
class Descendants extends DfsTraverser {
readonly count = new Int32Array(this.graph.nodeCount);
protected enterNode(person: number): boolean {
return true; // search from the children of every person
}
protected override leaveNode(person: number): void {
// Called after the whole subtree of the person: the counts of the children are
// complete.
for (const child of this.graph.outNodes(person)) {
this.count[person] += 1 + this.count[child];
}
}
}
const descendants = new Descendants(family);
descendants.run(ada);
// descendants.count: [9, 4, 3, 2, 0, 2, 0, 0, 0, 0] - Ada has 9, Ben 4, Cleo 3, ...
Full example
// Graph, a property of DfsTraverser, is the graph it searches.
private sealed class Descendants(Graph family) : DfsTraverser(family)
{
public int[] Count { get; } = new int[family.NodeCount];
protected override bool EnterNode(int person)
{
return true; // search from the children of every person
}
protected override void LeaveNode(int person)
{
// Called after the whole subtree of the person: the counts of the children
// are complete.
foreach (int child in Graph.OutNodes(person))
{
Count[person] += 1 + Count[child];
}
}
}
private static int[] CountDescendants(Graph family, int ada)
{
var descendants = new Descendants(family);
descendants.Run(ada);
// descendants.Count: [9, 4, 3, 2, 0, 2, 0, 0, 0, 0] - Ada has 9, Ben 4, Cleo 3,
// ...
return descendants.Count;
}
Full example

countcountcountCount holds the number of descendants of each person: 9 for Ada, 4 for Ben, 3 for Cleo, and 0 for each person without children, as in the picture after.