Tree data structure in C#

前端 未结 20 2642
梦如初夏
梦如初夏 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 09:01

    I've completed the code that @Berezh has shared.

      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;
            }
    
            public IEnumerator> GetEnumerator()
            {
                throw new NotImplementedException();
            }
    
            IEnumerator IEnumerable.GetEnumerator()
            {
                return (IEnumerator)GetEnumerator();
            }
        }
        public class TreeNodeEnum : IEnumerator>
        {
    
            int position = -1;
            public List> Nodes { get; set; }
    
            public TreeNode Current
            {
                get
                {
                    try
                    {
                        return Nodes[position];
                    }
                    catch (IndexOutOfRangeException)
                    {
                        throw new InvalidOperationException();
                    }
                }
            }
    
    
            object IEnumerator.Current
            {
                get
                {
                    return Current;
                }
            }
    
    
            public TreeNodeEnum(List> nodes)
            {
                Nodes = nodes;
            }
    
            public void Dispose()
            {
            }
    
            public bool MoveNext()
            {
                position++;
                return (position < Nodes.Count);
            }
    
            public void Reset()
            {
                position = -1;
            }
        }
    

提交回复
热议问题