subbft{
my ($f, $node) = @_;
my @children = $node->getAllChildren;
returnunless @children;
foreachmy $child ( @children ) {
$f->( $child->getNodeValue );
}
foreachmy $child ( @children ) {
bft($f, $child);
}
}
my $f = sub{ print $_[0], "\n" };
# create a tree and populate it, then call bft()
bft($f, $tree);
There are many ways to implement tree structures. Traversals can be somewhat implementation dependent. For trees with a get-children method, breadth-first traversal is pretty straightforward: start with the root, get its children, then loop over the children and recurse. This code was tested using CPAN's Tree::Simple.
class Tree
attr_accessor :value, :children
def initialize(value)
@value = value
@children = []
end
def traverse_breadth_first(f)
queue = []
queue.unshift(self)
while !(queue.empty?)
node = queue.pop
method(f).call(node.value)
node.children.each { |child| queue.unshift(child) }
end
end
end