二叉树的C#实现
二叉树的csharp实现,可用于数组排序
1 public class Tree<T> where T : IComparable<T>
2 {
3 private T data;
4 private Tree<T> left;
5 private Tree<T> right;
6
7 public Tree(T nodeValue)
8 {
9 this.data = nodeValue;
10 this.left = null;
11 this.right = null;
12 }
13
14 public T NodeData
15 {
16 get { return this.data; }
17 set { this.data = value; }
18 }
19 public Tree<T> LeftTree
20 {
21 get { return this.left; }
22 set { this.left = value; }
23 }
24 public Tree<T> RightTree
25 {
26 get { return this.right; }
27 set { this.right = value; }
28 }
29 /// <summary>
30 /// 插入节点
31 /// </summary>
32 /// <param name="newItem"></param>
33 public void Insert(T newItem)
34 {
35 T currentNodeValue = this.NodeData;
36 if (currentNodeValue.CompareTo(newItem) > 0)
37 {
38 if (this.LeftTree == null)
39 {
40 this.LeftTree = new Tree<T>(newItem);
41 }
42 else
43 {
44 this.LeftTree.Insert(newItem);
45 }
46 }
47 else
48 {
49 if (this.RightTree == null)
50 {
51 this.RightTree = new Tree<T>(newItem);
52 }
53 else
54 {
55 this.RightTree.Insert(newItem);
56 }
57 }
58 }
59 /// <summary>
60 /// 遍历树
61 /// </summary>
62 public void WalkTree()
63 {
64 if (this.LeftTree != null)
65 {
66 this.LeftTree.WalkTree();
67 }
68 Console.WriteLine(this.NodeData.ToString());
69 if (this.RightTree != null)
70 {
71 this.RightTree.WalkTree();
72 }
73 }
74 }