Objects that represent trees

Russell picture Russell · Nov 27, 2009 · Viewed 24.6k times · Source

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?

Answer

Bob picture Bob · Nov 27, 2009

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; }

  // ...
}