Logo

Programming-Idioms

  • C++
  • Haskell
  • Perl
  • PHP
  • C#

Idiom #18 Depth-first traversal of a tree

Call a function f on every node of a tree, in depth-first prefix order

A tree having 6 nodes, rooted at node 1
public static void Dfs(Action<Tree> f, Tree root) {
    f(root);
    foreach(var child in root.Children)
        Dfs(f, child);
} 
void dfs(const auto &tree, const auto &root)
{
	f(root);

	for (auto child : tree)
		dfs(tree, child);
}
preordered (Node pivot left right) = 
   pivot : preordered left ++ preordered right
preordered Ø = []
f <$> (preordered tree)
sub depth_first_traversal {
   my ($f, $treenode) = @_;
   $f->($treenode);
   depth_first_traversal($f, $_) for @{$treenode->{children}};
}

Assumes the tree is built from a hash, where the children property contains the current nodes children.
function dfs($f, $root)
{
    $f($root);
    foreach($root as $child)
    {
        dfs($child);
    }	
}

Here dfs is a recursive function to traverse the tree applying a function sent as the $f parameter
void prefixOrderTraversal(alias f)(ref Tree tree)
{
	f(tree);
	foreach (child; tree.children)
		prefixOrderTraversal!f(child);
}

This version takes f as a compile-time parameter, allowing inlining and other optimizations.

New implementation...