1 public class Tree<T> where T : IComparable<T> 2 { 3 /// <summary> 4 /// 定义树 5 /// </summary> 6 private T data; 7 private Tree<T> left; 8 private Tree<T> right; 9 10 /// <summary> 11 /// 构造函数 12 /// </summary> 13 /// <param name="nodeValue">二叉树根节点</param> 14 public Tree(T nodeValue) 15 { 16 this.data = nodeValue; 17 this.left = null; 18 this.right = null; 19 } 20 21 /// <summary> 22 /// 数据节点属性 23 /// </summary> 24 public T NodeData 25 { 26 get { return this.data; } 27 set { this.data = value; } 28 } 29 30 public Tree<T> leftTree 31 { 32 get { return this.left; } 33 set { this.left = value; } 34 } 35 36 public Tree<T> rightTree 37 { 38 get { return this.right; } 39 set { this.right = value; } 40 } 41 42 /// <summary> 43 /// 插入节点 小于该节点的放左侧,大于该节点的放右侧 44 /// </summary> 45 /// <param name="newItem"></param> 46 public void Insert(T newItem) 47 { 48 T currentNodeValue = this.NodeData; 49 if (currentNodeValue.CompareTo(newItem) > 0) 50 { 51 if (this.leftTree == null) 52 { 53 this.leftTree = new Tree<T>(newItem); 54 } 55 else 56 { 57 this.leftTree.Insert(newItem); 58 } 59 } 60 else 61 { 62 if (this.rightTree == null) 63 { 64 this.rightTree = new Tree<T>(newItem); 65 } 66 else 67 { 68 this.rightTree.Insert(newItem); 69 } 70 } 71 } 72 73 /// <summary> 74 /// 先序遍历 根 左 右 75 /// </summary> 76 /// <param name="root"></param> 77 public void PreOrderTree(Tree<T> root) 78 { 79 if (root != null) 80 { 81 Console.Write(root.NodeData); 82 PreOrderTree(root.leftTree); 83 PreOrderTree(root.rightTree); 84 } 85 } 86 87 /// <summary> 88 /// 中序遍历 左 根 右 89 /// </summary> 90 /// <param name="root"></param> 91 public void InOrderTree(Tree<T> root) 92 { 93 if (root != null) 94 { 95 InOrderTree(root.leftTree); 96 Console.Write(root.NodeData); 97 InOrderTree(root.rightTree); 98 } 99 } 100 101 /// <summary> 102 /// 后序遍历 左 右 根 103 /// </summary> 104 /// <param name="root"></param> 105 public void PostOrderTree(Tree<T> root) 106 { 107 if (root != null) 108 { 109 PostOrderTree(root.leftTree); 110 PostOrderTree(root.rightTree); 111 Console.Write(root.NodeData); 112 } 113 } 114 115 /// <summary> 116 /// 逐层遍历:从根节点开始,访问一个节点然后将左右子树的根节点依次放入链表中,删除该节点 117 /// 遍历到链表中没有数据为止 118 /// </summary> 119 public void WideOrderTree() 120 { 121 List<Tree<T>> nodeList = new List<Tree<T>>(); 122 nodeList.Add(this); 123 Tree<T> temp = null; 124 while (nodeList.Count > 0) 125 { 126 Console.Write(nodeList[0].NodeData); 127 temp = nodeList[0]; 128 nodeList.Remove(nodeList[0]); 129 if (temp.leftTree != null) 130 { 131 nodeList.Add(temp.leftTree); 132 } 133 if (temp.rightTree != null) 134 { 135 nodeList.Add(temp.rightTree); 136 } 137 } 138 Console.WriteLine(); 139 } 140 141 }
这是第二次让人讲二叉树了,一定不可以忘记!
时间: 2024-10-24 07:25:14