English 中文(简体)
Objects that represent trees [closed]
原标题:

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed last year.

The community reviewed whether to reopen this question last year and left it closed:

Opinion-based Update the question so it can be answered with facts and citations by editing this post.

Are there any objects in C# (or in .net) that represents a binary tree (or for curiosity) and n-ary tree?

I am not talking about presentation tree controls, but as model objects.

If not, are there any good external implementations?

最佳回答

The NGenerics project is a awesome collection of data structures and algorithms including a Binary Tree.

public class BinaryTree<T> : IVisitableCollection<T>, ITree<T>
{
  // Methods
  public void Add(BinaryTree<T> subtree);
  public virtual void breadthFirstTraversal(IVisitor<T> visitor);
  public virtual void 
         DepthFirstTraversal(OrderedVisitor<T> orderedVisitor);
  public BinaryTree<T> GetChild(int index);
  public bool Remove(BinaryTree<T> child);
  public virtual void RemoveLeft();
  public virtual void RemoveRight();

  // ...

  // Properties
  public virtual T Data { get; set; }
  public int Degree { get; }
  public virtual int Height { get; }
  public virtual bool IsLeafNode { get; }
  public BinaryTree<T> this[int i] { get; }
  public virtual BinaryTree<T> Left { get; set; }
  public virtual BinaryTree<T> Right { get; set; }
  
  // ...
}
问题回答

My attempt at a simple (non-balancing) binary search tree.

public sealed class BinarySearchTree<T> : IEnumerable<T>
{
   private readonly IComparer<T> _comparer;
   public BinaryTreeNode<T> Root { get; private set; }

   public BinarySearchTree()
   {    
   }

   public BinarySearchTree(IEnumerable<T> collection) : 
       this(collection, Comparer<T>.Default)
   {
   }

   public BinarySearchTree(IEnumerable<T> collection, IComparer<T> comparer)
   {
       if (collection == null) throw new ArgumentNullException("collection");
       if (comparer == null) throw new ArgumentNullException("comparer");

       _comparer = comparer;
       foreach (var item in collection)
           Add(item);
   }

   public BinarySearchTree(BinaryTreeNode<T> root)
   {
       Root = root;
   }

   public void Add(T val)   
   {    
       var newNode = new BinaryTreeNode<T>(val);
       if (Root == null)
       {
           Root = newNode;
           return;
       }

       Add(Root, newNode);  
   }

   void Add(BinaryTreeNode<T> root, BinaryTreeNode<T> node)
   {
       if (_comparer.Compare(node.Value, root.Value) <= 0)
       {
           if (root.Left == null)
               root.Left = node;
           else
               Add(root.Left, node);
       }
       else //node.Value > root.Value
       {
           if (root.Right == null)
               root.Right = node;
           else
               Add(root.Right, node);   
       }
   }

   public bool Contains(T val)
   {
       return Contains(Root, val);
   }

   bool Contains(BinaryTreeNode<T> node, T val)
   {
       if (node == null) 
           return false;

       var comparison = _comparer.Compare(val, node.Value);
       if (comparison == 0) //val = node.value
           return true;
       else if (comparison < 0) //val < node.Value
           return Contains(node.Left, val);
       else //val > node.Value
           return Contains(node.Right, val);
   }

   public T GetMinimum()
   {
       if (Root == null)
           return default(T);

       var node = Root;
       while (node.Left != null)
           node = node.Left;

       return node.Value;       
   }

   public T GetMaximum()
   {
       if (Root == null)
           return default(T);

       var node = Root;
       while (node.Right != null)
           node = node.Right;

       return node.Value;       
   }

   public IEnumerator<T> GetEnumerator()
   {
       return new BinaryTreeEnumerator<T>(Root);
   }

   IEnumerator IEnumerable.GetEnumerator()
   {
       return GetEnumerator();
   }
}

public sealed class BinaryTreeNode<T>
{
    public BinaryTreeNode<T> Left {get; set;}
    public BinaryTreeNode<T> Right {get; set;}      
    public T Value {get; private set;}

    public BinaryTreeNode(T val)
    {
        Value = val;
    }
}

public sealed class BinaryTreeEnumerator<T> : IEnumerator<T>
{
    private Stack<BinaryTreeNode<T>> _stack = new Stack<BinaryTreeNode<T>>();
    public T Current { get; private set; }

    public BinaryTreeEnumerator(BinaryTreeNode<T> root)
    {
        if (root == null)
            return; //empty root = Enumerable.Empty<T>()

        PushLeftBranch(root);
    }

    public void Dispose()
    {
        _stack = null; //help GC
    }

    public bool MoveNext()
    {
        if (_stack.Count == 0)
            return false;

        var node = _stack.Pop();
        Current = node.Value;

        if (node.Right != null)
            PushLeftBranch(node.Right);

        return true;
    }

    private void PushLeftBranch(BinaryTreeNode<T> node)
    {
        while (node != null)
        {
            _stack.Push(node);
            node = node.Left;
        }
    }

    public void Reset()
    {
        _stack.Clear();
    }

    object IEnumerator.Current
    {
        get { return Current; }
    }
}

I m not aware of one in the framework, but here is one implementation.

I am late to the party but this article says that SortedList and SortedDictionary are both based on trees.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签