Skip to content

Instantly share code, notes, and snippets.

@uucidl
Last active December 9, 2018 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uucidl/fef93303a243e976070528cf3db500a6 to your computer and use it in GitHub Desktop.
Save uucidl/fef93303a243e976070528cf3db500a6 to your computer and use it in GitHub Desktop.
Traversing Hierarchies
// Depth first traversal algorithm.
//
// (credit to Alexander Stepanov in Elements Of Programming)
//
// One of the benefits is that the visitor can implement pre or post traversal algorithms, and combine them in one single piece.
//
// @generic in T, the node value type
func traverse_children_recursively(tree_root: T*, step_visitor: func(step: TraversalStep, node: T*))
{
step_visitor(TraversalStep_PRE, tree_root);
last_child := children_last(tree_root);
child := children_first(tree_root);
while (child != last_child) {
traverse_children_recursively(child, step_visitor);
child = next_child(child);
}
step_visitor(TraversalStep_POST, tree_root);
}
enum TraversalStep
{
TraversalStep_PRE,
TraversalStep_POST,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment