C#实现树结构
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#实现树结构,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2531字,纯文字阅读大概需要4分钟。
内容图文
![C#实现树结构](/upload/InfoBanner/zyjiaocheng/1075/8599c261deb34729a232f6885191f1e7.jpg)
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吗?所以是一回事。。。
原文:http://my.oschina.net/somereasons/blog/485284
内容总结
以上是互联网集市为您收集整理的C#实现树结构全部内容,希望文章能够帮你解决C#实现树结构所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。