Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In C#, you can implement an iterator method with the signature like this:

    public static IEnumerable<TNode> DepthFirstTraverse<TNode>(
        TNode root,
        Func<TNode, IEnumerable<TNode>> children
    )
You can then just ‘foreach’ over it.

This doesn’t require the whole tree to be in-memory. Optimal implementation would recurse via programmer-controlled stack (instead of language-controlled) to avoid nested iterators.

Here is a TypeScript version:

    function* traverseDepthFirst<T>(
        root: T,
        children: (parent: T) => Iterable<T>
    )
A similar approach should be possible in any language which supports iterators/generators.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: