樹是一種非線性結構,樹的本質是將一些節點由邊連接起來,形成層級的結構,即1:N的關系,下面是手動構建數據之間的關系:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Tree3 { //手動構建節點之間的關系 public class Program { static void Main(string[] args) { Node<string> rootNode =BinTree(); Console.WriteLine("先序遍歷方法遍歷二叉樹: "); PreOrde(rootNode); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("中序遍歷方法遍歷二叉樹:"); InOrde(rootNode); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("後序遍歷方法遍歷二叉樹:"); AfterOrde(rootNode); Console.ReadKey(); } /// <summary> /// 構建二叉樹 /// </summary> /// <returns></returns> public static Node<string> BinTree() { Node<string>[] binTree = new Node<string>[11]; //創建節點 binTree[0] = new Node<string>("A"); binTree[1] = new Node<string>("B"); binTree[2] = new Node<string>("C"); binTree[3] = new Node<string>("D"); binTree[4] = new Node<string>("E"); binTree[5] = new Node<string>("F"); binTree[6] = new Node<string>("G"); binTree[7] = new Node<string>("H"); binTree[8] = new Node<string>("J"); binTree[9] = new Node<string>("K"); binTree[10] = new Node<string>("L"); //構建關系 binTree[0].LNode = binTree[1]; binTree[0].RNode = binTree[2]; binTree[1].LNode = binTree[3]; binTree[1].RNode = binTree[4]; binTree[2].LNode = binTree[6]; binTree[2].RNode = binTree[7]; binTree[6].RNode = binTree[8]; binTree[7].RNode = binTree[9]; binTree[8].RNode = binTree[10]; //返回跟節點 return binTree[0]; } /// <summary> /// 先序遍歷(先訪問跟節點->在訪問左孩子->在訪問右孩子)遞歸 /// 注意的是:遍歷左右子樹時仍然采用中序遍歷方法。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="rootNode"></param> public static void PreOrde<T>(Node<T> rootNode) { if (rootNode != null) { Console.Write(string.Format("{0} ", rootNode.Data)); PreOrde(rootNode.LNode); PreOrde(rootNode.RNode); } } /// <summary> /// 中序遍歷(先訪問左節點->在訪問跟節點->在訪問右孩子)遞歸 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="rootNode"></param> public static void InOrde<T>(Node<T> rootNode) { if (rootNode != null) { InOrde(rootNode.LNode); Console.Write(string.Format("{0} ", rootNode.Data)); InOrde(rootNode.RNode); } } /// <summary> /// 後序遍歷(先訪問左節點->在訪問右節點->在訪問跟孩子)遞歸 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="rootNode"></param> public static void AfterOrde<T>(Node<T> rootNode) { if (rootNode != null) { AfterOrde(rootNode.LNode); AfterOrde(rootNode.RNode); Console.Write(string.Format("{0} ", rootNode.Data)); } } } //節點類 public class Node<T> { private T data; /// <summary> /// 數據 /// </summary> public T Data { get { return data; } set { data = value; } } private Node<T> lnode; /// <summary> /// 左孩子 /// </summary> public Node<T> LNode { get { return lnode; } set { lnode = value; } } private Node<T> rnode; /// <summary> /// 右孩子 /// </summary> public Node<T> RNode { get { return rnode; } set { rnode = value; } } /// <summary> /// 無參構造函數 /// </summary> public Node() { } /// <summary> /// 節點構造函數 /// </summary> /// <param name="data"></param> public Node(T data) { this.data = data; } } }
運行結果: