2015年8月21日 星期五

Tree data structure in C#

elegate void TreeVisitor<T>(T nodeData);

class NTree<T>
{
    private T data;
    private 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);
    }
}
Simple recursive implementation... < 40 lines of code... You just need to keep a reference to the root of the tree outside of the class, or wrap it in another class, maybe rename to TreeNode??

Yet another tree structure:
public class TreeNode<T> : IEnumerable<TreeNode<T>>
{

    public T Data { get; set; }
    public TreeNode<T> Parent { get; set; }
    public ICollection<TreeNode<T>> Children { get; set; }

    public TreeNode(T data)
    {
        this.Data = data;
        this.Children = new LinkedList<TreeNode<T>>();
    }

    public TreeNode<T> AddChild(T child)
    {
        TreeNode<T> childNode = new TreeNode<T>(child) { Parent = this };
        this.Children.Add(childNode);
        return childNode;
    }

    // other features ...
}
Sample usage:
TreeNode root = new TreeNode("root");
{
    TreeNode node0 = root.AddChild("node0");
    TreeNode node1 = root.AddChild("node1");
    TreeNode node2 = root.AddChild("node2");
    {
        TreeNode node20 = node2.AddChild(null);
        TreeNode node21 = node2.AddChild("node21");
        {
            TreeNode node210 = node21.AddChild("node210");
            TreeNode node211 = node21.AddChild("node211");
        }
    }
    TreeNode node3 = root.AddChild("node3");
    {
        TreeNode node30 = node3.AddChild("node30");
    }
}
BONUS
See fully-fledged tree with:
  • iterator
  • searching
  • Java/C#

refer to:
http://stackoverflow.com/questions/66893/tree-data-structure-in-c-sharp/2012855#2012855

沒有留言:

張貼留言