本文共 2911 字,大约阅读时间需要 9 分钟。
class Tree{ private T[] data; private int count; public Tree(int capacity) { data=new T[capacity]; count = 0; } /// /// 添加数据 /// /// public void AddValue(T value) { if (count>data.Length) { throw new IndexOutOfRangeException(); } data[count] = value; count++; }
////// 前序遍历 /// public void PeorderTraversal(int index=0) { //判断索引是否超出容量 //判断tree是否为空 //先跟后左再右 if (index>data.Length-1) { return; } if (data[index].Equals(-1)) { return; } int number = index + 1; int left = 2 * number; int right = left + 1; Console.Write(data[index]+" "); PeorderTraversal(left-1); PeorderTraversal(right-1); } ////// 中序遍历 /// public void InorderTraversal(int index=0) { if (index > data.Length - 1) { return; } if (data[index].Equals(-1)) { return; } int number = index + 1; int left = 2 * number; int right = left + 1; InorderTraversal(left - 1); Console.Write(data[index] + " "); InorderTraversal(right - 1); } ////// 后续遍历 /// public void PostorderTraversal(int index=0) { if (index > data.Length - 1) { return; } if (data[index].Equals(-1)) { return; } int number = index + 1; int left = 2 * number; int right = left + 1; PostorderTraversal(left-1); PostorderTraversal(right-1); Console.Write(data[index] + " "); } ////// 层序遍历 /// public void SequenceTraversal() { for (int i = 0; i < data.Length; i++) { if (data[i].Equals(-1)) { continue; } Console.Write(data[i]+" "); } } }
class Program { static void Main(string[] args) { char[] sum = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'}; Treetree=new Tree (10); for (int i = 0; i < sum.Length; i++) { tree.AddValue(sum[i]); } // tree.PeorderTraversal(); //tree.InorderTraversal(); //tree.PostorderTraversal(); tree.SequenceTraversal(); Console.ReadKey(); } }
转载地址:http://hdrxo.baihongyu.com/