public interface IBinTree<T> : IDateStructrue { IList<T> PreOrder(); IList<T> InOrder(); IList<T> PostOrder(); IList<T> LevelOrder(); void PreCreator(T[] items); BTNode<T> Root { get;} int LeafCount { get;} } namespace DateStructrue { public class BTNode<T> { public T Item { get; set; } public BTNode<T> RNode { get; set; } public BTNode<T> LNode { get; set; } public BTNode(T item) : this(item, null, null) { } public BTNode(T item, BTNode<T> lNode, BTNode<T> rNode) { this.Item = item; this.LNode = lNode; this.RNode = rNode; } } public class BinTree<T>:IBinTree<T> { private T[] _items; private int i=-1; private IList<T> _PreList = new List<T>(); private IList<T> _InList = new List<T>(); private IList<T> _PostList = new List<T>(); private IList<T> _LevelList = new List<T>(); #region IBinTree<T> Members public IList<T> PreOrder() { return Order(this.Root, OrderType.Pre); } public IList<T> InOrder() { return Order(this.Root, OrderType.In); } public IList<T> PostOrder() { return Order(this.Root, OrderType.Post); } public IList<T> LevelOrder() { Queue<T> q = new Queue<T>(); var node = this.Root; q.EnQueue(node.Item); while (q.Count > 0) { this._LevelList.Add(q.DeQueue()); if (node.LNode != null) q.EnQueue(node.LNode.Item); if (node.RNode != null) q.EnQueue(node.RNode.Item); } } public void PreCreator(T[] items) { this._items = items; if (!Check) return; BTNode<T> head = PreCreatorT(); this.Root = head; } public int LeafCount { get { return CountLeaf(this.Root); } } public BTNode<T> Root { get; private set; } #endregion #region IDateStructrue Members public int Count { get { return 0; } } public void Clear() { this.Root = null; } public bool IsEmpty { get { return this.Root == null; } } #endregion #region Helper private BTNode<T> PreCreatorT() { i++; if (_items[i].Equals(default(T))) return null; else { BTNode<T> node = new BTNode<T>(_items[i]); node.LNode = PreCreatorT(); node.RNode = PreCreatorT(); return node; } } private bool Check { get { int nullCount = 0; int dataCount = 0; foreach (T t in _items) { if (t.Equals(default(T))) nullCount++; else dataCount++; } return nullCount == dataCount + 1; } } private IList<T> Order(BTNode<T> node, OrderType type) { if (node == null) return null; switch (type) { case OrderType.Pre: this._PreList.Add(node.Item); Order(node.LNode, type); Order(node.RNode, type); return this._PreList; case OrderType.In: Order(node.LNode, type); this._InList.Add(node.Item); Order(node.RNode, type); return this._InList; case OrderType.Post: Order(node.LNode, type); Order(node.RNode, type); this._PostList.Add(node.Item); return this._PostList; default: return null; } } private int CountLeaf(BTNode<T> node) { if (node == null) return 0; else { if (node.RNode == null && node.LNode == null) return 1; else return CountLeaf(node.LNode) + CountLeaf(node.RNode); } } #endregion enum OrderType { Pre, In, Post } } }