还是贴上一个简化的版本吧
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace NFox.Collections
- {
- /// <summary>
- /// 深度优先遍历模式
- /// </summary>
- public enum DepthSearchModeType
- {
- /// <summary>
- /// 前序遍历
- /// </summary>
- Preorder,
- /// <summary>
- /// 中序遍历
- /// </summary>
- //Inorder,
- /// <summary>
- /// 后序遍历
- /// </summary>
- Postorder
- }
- public class Tree<T> : List<Tree<T>>
- {
- public T Value { get; set; }
- public Tree<T> Parent
- { private set; get; }
- public bool IsRoot
- {
- get { return Parent == null; }
- }
- public bool IsLeaf
- {
- get { return Count == 0; }
- }
- public Tree<T> Root
- {
- get
- {
- var node = this;
- while (node.Parent != null)
- {
- node = node.Parent;
- }
- return node;
- }
- }
- public Tree(){ }
- public Tree(T value)
- {
- Value = value;
- }
- public bool IsAncestorOf(Tree<T> other)
- {
- Tree<T> node = other;
- while (node.Parent != null)
- {
- node = node.Parent;
- if (this == node)
- return true;
- }
- return false;
- }
- public bool IsChildOf(Tree<T> other)
- {
- return other.IsAncestorOf(this);
- }
- public List<Tree<T>> Path
- {
- get
- {
- List<Tree<T>> lst = new List<Tree<T>> { this };
- Tree<T> node = this;
- while (node.Parent != null)
- {
- node = node.Parent;
- lst.Insert(0, node);
- }
- return lst;
- }
- }
- public int Depth
- {
- get { return Path.Count - 1; }
- }
- public new void Insert(int index, Tree<T> node)
- {
- node.Parent = this;
- base.Insert(index, node);
- }
- public void InsertBefore(Tree<T> node, T value)
- {
- Insert(IndexOf(node), new Tree<T>(value));
- }
- public void InsertAfter(Tree<T> node, T value)
- {
- Insert(IndexOf(node) + 1, new Tree<T>(value));
- }
- public new void Add(Tree<T> node)
- {
- node.Parent = this;
- base.Add(node);
- }
- public void Add(T value)
- {
- Add(new Tree<T>(value));
- }
- public new void AddRange(IEnumerable<Tree<T>> collection)
- {
- foreach (var tree in collection)
- tree.Parent = this;
- base.AddRange(collection);
- }
- public void AddRange(IEnumerable<T> collection)
- {
- AddRange(collection.Select(value => new Tree<T>(value)));
- }
- public void RemoveAll(Predicate<T> match)
- {
- base.RemoveAll(tree => match(tree.Value));
- }
- //深度优先
- public void SearchByDepthFirst(DepthSearchModeType mode, Action<T> action)
- {
- if (mode == DepthSearchModeType.Preorder)
- action(this.Value);
- foreach (Tree<T> node in this)
- node.SearchByDepthFirst(mode, action);
- if (mode == DepthSearchModeType.Postorder)
- action(this.Value);
- }
- //广度优先
- public void SearchByBreadthFirst(Action<T> action)
- {
- Queue<Tree<T>> q = new Queue<Tree<T>>();
- q.Enqueue(this);
- while (q.Count > 0)
- {
- Tree<T> node = q.Dequeue();
- action(node.Value);
- node.ForEach(child => q.Enqueue(child));
- }
- }
- }
- }
|