树是一种非线性结构,树的本质是将一些节点由边连接起来,形成层级的结构,即1:N的关系,下面是手动构建数据之间的关系: using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Tree3{ //手动构建节点之间的关系 public class Program { static void Main(string[] args) { NoderootNode =BinTree(); Console.WriteLine("先序遍历方法遍历二叉树: "); PreOrde(rootNode); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("中序遍历方法遍历二叉树:"); InOrde(rootNode); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("后序遍历方法遍历二叉树:"); AfterOrde(rootNode); Console.ReadKey(); } /// /// 构建二叉树 /// ///public static Node BinTree() { Node [] binTree = new Node [11]; //创建节点 binTree[0] = new Node ("A"); binTree[1] = new Node ("B"); binTree[2] = new Node ("C"); binTree[3] = new Node ("D"); binTree[4] = new Node ("E"); binTree[5] = new Node ("F"); binTree[6] = new Node ("G"); binTree[7] = new Node ("H"); binTree[8] = new Node ("J"); binTree[9] = new Node ("K"); binTree[10] = new Node ("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]; } /// /// 先序遍历(先访问跟节点->在访问左孩子->在访问右孩子)递归 /// 注意的是:遍历左右子树时仍然采用中序遍历方法。 /// ////// public static void PreOrde (Node rootNode) { if (rootNode != null) { Console.Write(string.Format("{0} ", rootNode.Data)); PreOrde(rootNode.LNode); PreOrde(rootNode.RNode); } } /// /// 中序遍历(先访问左节点->在访问跟节点->在访问右孩子)递归 /// ////// public static void InOrde (Node rootNode) { if (rootNode != null) { InOrde(rootNode.LNode); Console.Write(string.Format("{0} ", rootNode.Data)); InOrde(rootNode.RNode); } } /// /// 后序遍历(先访问左节点->在访问右节点->在访问跟孩子)递归 /// ////// public static void AfterOrde (Node rootNode) { if (rootNode != null) { AfterOrde(rootNode.LNode); AfterOrde(rootNode.RNode); Console.Write(string.Format("{0} ", rootNode.Data)); } } } //节点类 public class Node { private T data; /// /// 数据 /// public T Data { get { return data; } set { data = value; } } private Nodelnode; /// /// 左孩子 /// public NodeLNode { get { return lnode; } set { lnode = value; } } private Node rnode; /// /// 右孩子 /// public NodeRNode { get { return rnode; } set { rnode = value; } } /// /// 无参构造函数 /// public Node() { } ////// 节点构造函数 /// /// public Node(T data) { this.data = data; } }} 运行结果: