Tree data structure in C#

前端 未结 20 2147
梦如初夏
梦如初夏 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:50

    Here's my own:

    class Program
    {
        static void Main(string[] args)
        {
            var tree = new Tree<string>()
                .Begin("Fastfood")
                    .Begin("Pizza")
                        .Add("Margherita")
                        .Add("Marinara")
                    .End()
                    .Begin("Burger")
                        .Add("Cheese burger")
                        .Add("Chili burger")
                        .Add("Rice burger")
                    .End()
                .End();
    
            tree.Nodes.ForEach(p => PrintNode(p, 0));
            Console.ReadKey();
        }
    
        static void PrintNode<T>(TreeNode<T> node, int level)
        {
            Console.WriteLine("{0}{1}", new string(' ', level * 3), node.Value);
            level++;
            node.Children.ForEach(p => PrintNode(p, level));
        }
    }
    
    public class Tree<T>
    {
        private Stack<TreeNode<T>> m_Stack = new Stack<TreeNode<T>>();
    
        public List<TreeNode<T>> Nodes { get; } = new List<TreeNode<T>>();
    
        public Tree<T> Begin(T val)
        {
            if (m_Stack.Count == 0)
            {
                var node = new TreeNode<T>(val, null);
                Nodes.Add(node);
                m_Stack.Push(node);
            }
            else
            {
                var node = m_Stack.Peek().Add(val);
                m_Stack.Push(node);
            }
    
            return this;
        }
    
        public Tree<T> Add(T val)
        {
            m_Stack.Peek().Add(val);
            return this;
        }
    
        public Tree<T> End()
        {
            m_Stack.Pop();
            return this;
        }
    }
    
    public class TreeNode<T>
    {
        public T Value { get; }
        public TreeNode<T> Parent { get; }
        public List<TreeNode<T>> Children { get; }
    
        public TreeNode(T val, TreeNode<T> parent)
        {
            Value = val;
            Parent = parent;
            Children = new List<TreeNode<T>>();
        }
    
        public TreeNode<T> Add(T val)
        {
            var node = new TreeNode<T>(val, this);
            Children.Add(node);
            return node;
        }
    }
    

    Output:

    Fastfood
       Pizza
          Margherita
          Marinara
       Burger
          Cheese burger
          Chili burger
          Rice burger
    
    0 讨论(0)
  • 2020-11-22 08:51

    Here's mine, which is very similar to Aaron Gage's, just a little more conventional, in my opinion. For my purposes, I haven't ran into any performance issues with List<T>. It would be easy enough to switch to a LinkedList if needed.


    namespace Overby.Collections
    {
        public class TreeNode<T>
        {
            private readonly T _value;
            private readonly List<TreeNode<T>> _children = new List<TreeNode<T>>();
    
            public TreeNode(T value)
            {
                _value = value;
            }
    
            public TreeNode<T> this[int i]
            {
                get { return _children[i]; }
            }
    
            public TreeNode<T> Parent { get; private set; }
    
            public T Value { get { return _value; } }
    
            public ReadOnlyCollection<TreeNode<T>> Children
            {
                get { return _children.AsReadOnly(); }
            }
    
            public TreeNode<T> AddChild(T value)
            {
                var node = new TreeNode<T>(value) {Parent = this};
                _children.Add(node);
                return node;
            }
    
            public TreeNode<T>[] AddChildren(params T[] values)
            {
                return values.Select(AddChild).ToArray();
            }
    
            public bool RemoveChild(TreeNode<T> node)
            {
                return _children.Remove(node);
            }
    
            public void Traverse(Action<T> action)
            {
                action(Value);
                foreach (var child in _children)
                    child.Traverse(action);
            }
    
            public IEnumerable<T> Flatten()
            {
                return new[] {Value}.Concat(_children.SelectMany(x => x.Flatten()));
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:51

    If you are going to display this tree on the GUI, you can use TreeView and TreeNode. (I suppose technically you can create a TreeNode without putting it on a GUI, but it does have more overhead than a simple homegrown TreeNode implementation.)

    0 讨论(0)
  • 2020-11-22 08:53

    Try this simple sample.

    public class TreeNode<TValue>
    {
        #region Properties
        public TValue Value { get; set; }
        public List<TreeNode<TValue>> Children { get; private set; }
        public bool HasChild { get { return Children.Any(); } }
        #endregion
        #region Constructor
        public TreeNode()
        {
            this.Children = new List<TreeNode<TValue>>();
        }
        public TreeNode(TValue value)
            : this()
        {
            this.Value = value;
        }
        #endregion
        #region Methods
        public void AddChild(TreeNode<TValue> treeNode)
        {
            Children.Add(treeNode);
        }
        public void AddChild(TValue value)
        {
            var treeNode = new TreeNode<TValue>(value);
            AddChild(treeNode);
        }
        #endregion
    }
    
    0 讨论(0)
  • 2020-11-22 08:55
    delegate 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??

    0 讨论(0)
  • 2020-11-22 08:58

    My best advice would be that there is no standard tree data structure because there are so many ways you could implement it that it would be impossible to cover all bases with one solution. The more specific a solution, the less likely it is applicable to any given problem. I even get annoyed with LinkedList - what if I want a circular linked list?

    The basic structure you'll need to implement will be a collection of nodes, and here are some options to get you started. Let's assume that the class Node is the base class of the entire solution.

    If you need to only navigate down the tree, then a Node class needs a List of children.

    If you need to navigate up the tree, then the Node class needs a link to its parent node.

    Build an AddChild method that takes care of all the minutia of these two points and any other business logic that must be implemented (child limits, sorting the children, etc.)

    0 讨论(0)
提交回复
热议问题