Tree data structure in C#

前端 未结 20 2643
梦如初夏
梦如初夏 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条回答
  •  梦谈多话
    2020-11-22 08:55

    delegate void TreeVisitor(T nodeData);
    
    class NTree
    {
        private T data;
        private LinkedList> children;
    
        public NTree(T data)
        {
             this.data = data;
            children = new LinkedList>();
        }
    
        public void AddChild(T data)
        {
            children.AddFirst(new NTree(data));
        }
    
        public NTree GetChild(int i)
        {
            foreach (NTree n in children)
                if (--i == 0)
                    return n;
            return null;
        }
    
        public void Traverse(NTree node, TreeVisitor visitor)
        {
            visitor(node.data);
            foreach (NTree 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??

提交回复
热议问题