Example usage of a custom delegate in c#

Posted by Freakishly on Stack Overflow See other posts from Stack Overflow or by Freakishly
Published on 2011-01-17T01:38:39Z Indexed on 2011/01/17 1:53 UTC
Read the original article Hit count: 600

Filed under:
|
|
|

Hi,

I found this question on SO about a tree implementation in C#. I have no idea about delegates and I was wondering how the following code could be used to implement a tree. Also, what would be the most efficient way to keep a track of parent nodes?

delegate void TreeVisitor<T>(T nodeData);

class NTree<T>
{
    T data;
    LinkedList<NTree<T>> children;

    public NTree(T data)
    {
        this.data = data;
        children = new LinkedList<NTree<T>>();
    }

    public void addChild(T data)
    {
        children.AddFirst(new NTree<T>(data));
    }

    public NTree<T> getChild(int i)
    {
        foreach (NTree<T> n in children)
            if (--i == 0) return n;
        return null;
    }

    public void traverse(NTree<T> node, TreeVisitor<T> visitor)
    {
        visitor(node.data);
        foreach (NTree<T> kid in node.children)
            traverse(kid, visitor);
    }        
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about delegates