假定給定數組:node
int[] bArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 實現如下功能。git
class Node { public Node leftChild { get; set; } public Node rightChild { get; set; } public int data { get; set; } public Node(int newData) { leftChild = null; rightChild = null; data = newData; } }
/// <summary> /// 建立二叉樹樹 /// </summary> /// <param name="arr"></param> /// <returns></returns> static List<Node> createdBinTree(int[] arr) { List<Node> nodeList = new List<Node>(); //將數組值依次轉入Node節點 for (int i = 0; i < arr.Length; i++) { nodeList.Add(new Node(arr[i])); } for (int j = 0; j < arr.Length/2-1; j++) { //左孩子 nodeList[j].leftChild = nodeList[j * 2 + 1]; //右孩子 nodeList[j].rightChild = nodeList[j * 2 + 2]; } //最後一個節點:由於最後一個父節點可能沒有右孩子,因此單獨拿出來處理 int last = arr.Length / 2 - 1; //左孩子 nodeList[last].leftChild = nodeList[last * 2 + 1]; //右孩子 if (arr.Length % 2 == 1) { nodeList[last].rightChild = nodeList[last * 2 + 2]; } return nodeList; }
/// <summary> /// 前序遍歷 /// </summary> /// <param name="node"></param> static void preOrder(Node node) { if (node == null) return; System.Console.WriteLine(node.data+" "); preOrder(node.leftChild); preOrder(node.rightChild); }
/// <summary> /// 中序遍歷 /// </summary> /// <param name="node"></param> static void inOrder(Node node) { if (node == null) return; inOrder(node.leftChild); System.Console.WriteLine(node.data+" "); inOrder(node.rightChild); }
/// <summary> /// 後序遍歷 /// </summary> /// <param name="node"></param> static void postOrder(Node node) { if (node == null) return; postOrder(node.leftChild); postOrder(node.rightChild); System.Console.WriteLine(node.data+" "); }
int[] bArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<Node> nodeList = createdBinTree(bArr); System.Console.WriteLine("先序遍歷"); preOrder(nodeList[0]); System.Console.WriteLine("中序遍歷"); inOrder(nodeList[0]); System.Console.WriteLine("後序遍歷"); postOrder(nodeList[0]); System.Console.ReadKey();