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; } } }
这是一颗可以遍历的树~~~~用的是前序遍历
怎么用呢?
把你的类继承,带上附加信息就行。
就像这样
public class FileNode: TreeNode { public string Name { get; set; } }
调用的时候就这样
private void button1_Click(object sender, EventArgs e) { FileNode a1 = new FileNode() { Name = "1" }; FileNode a2 = new FileNode() { Name = "2" }; FileNode a3 = new FileNode() { Name = "3" }; FileNode a4 = new FileNode() { Name = "4" }; FileNode a5 = new FileNode() { Name = "5" }; FileNode a6 = new FileNode() { Name = "6" }; FileNode a7 = new FileNode() { Name = "7" }; a1.AddChild(a2, a3); a2.AddChild(a4, a5); a3.AddChild(a6); a6.AddChild(a7); a3.RemoveChild(a6); textBox1.Text = string.Empty; foreach (FileNode node in a1) { textBox1.Text += node.Name; } }
有的同学要问了。不对劲啊,这个是treenode啊,不是tree啊。
可是可是。。。tree的每一个节点都可以带字节点,不都是可以看作一个tree吗?所以是一回事。。。
时间: 2024-10-29 07:32:20