C#实现树结构
标签:
public class TreeNode : IEnumerable { public TreeNode() { Childs = new List<TreeNode>(); } public TreeNode Parent { get; set; } public List<TreeNode> Childs { get; protected set; } public void AddChild(params TreeNode[] nodes) { for (int i = 0; i < nodes.Length; i++) { nodes[i].Parent = this; Childs.Add(nodes[i]); } } public void RemoveChild(params TreeNode[] nodes) { for (int i = 0; i < nodes.Length; i++) { nodes[i].Parent = null; Childs.Remove(nodes[i]); } } public List<TreeNode> GetBrothers() { if (this.Parent != null) { TreeNode[] childsOfPapa = new TreeNode[Parent.Childs.Count]; this.Parent.Childs.CopyTo(childsOfPapa); List<TreeNode> childsOfPapaList = childsOfPapa.ToList(); childsOfPapaList.Remove(this); return childsOfPapaList; } return null; } public IEnumerator GetEnumerator() { return new TreeEnum(this); } } class TreeEnum : IEnumerator { private TreeNode rootNode; private TreeNode curNode; Queue<TreeNode> collection; public TreeEnum(TreeNode _collection) { rootNode = _collection; collection = new Queue<TreeNode>(); FillQueue(rootNode); curNode = rootNode; } private void FillQueue(TreeNode _collection) { //前序遍历 collection.Enqueue(_collection); if (_collection.Childs != null && _collection.Childs.Count > 0) foreach (TreeNode child in _collection.Childs) { FillQueue(child); } } public bool MoveNext() { if (collection.Count > 0) { curNode = collection.Dequeue(); return true; } else return false; } public void Reset() { collection = new Queue<TreeNode>(); FillQueue(rootNode); curNode = rootNode; } public TreeNode Current { get { return curNode; } } object IEnumerator.Current { get { return Current; } } }这是一颗可以遍历的树~~~~用的是前序遍历
怎么用呢?
把你的类继承,,带上附加信息就行。
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69109.html