public class BoTree<T> { public BoTree() { nodes = new List<BoTree<T>>(); } public BoTree(T data) { this.Data = data; nodes = new List<BoTree<T>>(); } private BoTree<T> parent; /// <summary> /// 父結點 /// </summary> public BoTree<T> Parent { get { return parent; } } /// <summary> /// 結點數據 /// </summary> public T Data { get; set; } private List<BoTree<T>> nodes; /// <summary> /// 子結點 /// </summary> public List<BoTree<T>> Nodes { get { return nodes; } } /// <summary> /// 添加結點 /// </summary> /// <param name="node">結點</param> public void AddNode(BoTree<T> node) { if (!nodes.Contains(node)) { node.parent = this; nodes.Add(node); } } /// <summary> /// 添加結點 /// </summary> /// <param name="nodes">結點集合</param> public void AddNode(List<BoTree<T>> nodes) { foreach (var node in nodes) { if (!nodes.Contains(node)) { node.parent = this; nodes.Add(node); } } } /// <summary> /// 移除結點 /// </summary> /// <param name="node"></param> public void Remove(BoTree<T> node) { if (nodes.Contains(node)) nodes.Remove(node); } /// <summary> /// 清空結點集合 /// </summary> public void RemoveAll() { nodes.Clear(); } }
測試: 首先創建一個學生類(任意)
public class Student { public Student(string name, string sex, int age) { this.Name = name; this.Sex = sex; this.Age = age; } public string Name { get; set; } public string Sex { get; set; } public int Age { get; set; } }
初始化樹:
BoTree<Student> tree1 = new BoTree<Student>(); tree1.Data = new Student("小波1", "男", 18); BoTree<Student> tree2 = new BoTree<Student>(); tree2.Data = new Student("小波2", "男", 19); BoTree<Student> tree3 = new BoTree<Student>(); tree3.Data = new Student("小波3", "男", 20); BoTree<Student> tree4 = new BoTree<Student>(); tree4.Data = new Student("小波4", "男", 21); tree1.AddNode(tree2); tree1.AddNode(tree3); tree3.AddNode(tree4);