Tree data structure in C#

前端 未结 20 2191
梦如初夏
梦如初夏 2020-11-22 08:30

I was looking for a tree or graph data structure in C# but I guess there isn\'t one provided. An Extensive Examination of Data Structures Using C# 2.0 explains a bit about w

20条回答
  •  -上瘾入骨i
    2020-11-22 09:06

    Yet another tree structure:

    public class TreeNode : IEnumerable>
    {
    
        public T Data { get; set; }
        public TreeNode Parent { get; set; }
        public ICollection> Children { get; set; }
    
        public TreeNode(T data)
        {
            this.Data = data;
            this.Children = new LinkedList>();
        }
    
        public TreeNode AddChild(T child)
        {
            TreeNode childNode = new TreeNode(child) { Parent = this };
            this.Children.Add(childNode);
            return childNode;
        }
    
        ... // for iterator details see below link
    }
    

    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#

    https://github.com/gt4dev/yet-another-tree-structure

提交回复
热议问题