This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
public static void Dfs(Action<Tree> f, Tree root) {
f(root);
foreach(var child in root.Children)
Dfs(f, child);
}
recursive subroutine depth_first (node, f)
type (tr), pointer :: node
interface
subroutine f(node)
import
type(tr), pointer :: node
end subroutine f
end interface
if (associated(node%left)) call depth_first (node, f)
if (associated(node%right)) call depth_first (node, f)
call f(node)
end subroutine depth_first
func (t *Tree) Dfs(f func(*Tree)) {
if t == nil {
return
}
f(t)
for _, child := range t.Children {
child.Dfs(f)
}
}
The function f is a parameter of the traversal method Dfs .
The traversal is prefix because f is applied to current node first.
The traversal is prefix because f is applied to current node first.
func (t *Tree[L]) Dfs(f func(*Tree[L])) {
if t == nil {
return
}
f(t)
for _, child := range t.Children {
child.Dfs(f)
}
}
The type parameter L is for arbitrary node label data
pub struct Tree<V> {
children: Vec<Tree<V>>,
value: V
}
impl<V> Tree<V> {
pub fn dfs<F: Fn(&V)>(&self, f: F) {
self.dfs_helper(&f);
}
fn dfs_helper<F: Fn(&V)>(&self, f: &F) {
(f)(&self.value);
for child in &self.children {
child.dfs_helper(f)
}
}
// ...
}
The actual idiomatic way to do this is to implement an iterator.