using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 树 { public class TreeNode<T> { public T Data; public TreeNode() { Data = default(T); } public TreeNode( T data) { Data = data; } } public class BinaryTree<T> where T: IComparable<T> { public TreeNode<T> Root;//根节点 public BinaryTree<T> LeftTree;//左子树 public BinaryTree<T> RightTree;//右子树 public BinaryTree(T data) { Root = new TreeNode<T>(data); LeftTree = null; RightTree = null; } public void Create(T data) { T tmpData = this.Root.Data; if(tmpData.CompareTo(data)>0) { if (this.LeftTree == null) { this.LeftTree = new BinaryTree<T>(data); } else { this.LeftTree.Create(data); } }else { if (this.RightTree == null) { this.RightTree = new BinaryTree<T>(data); } else { this.RightTree.Create(data); } } } /// <summary> /// 前序遍历 /// </summary> public void FrontOver() { Console.WriteLine(Root.Data); if(this.LeftTree!=null) { this.LeftTree.FrontOver(); } if (this.RightTree != null) { this.RightTree.FrontOver(); } } /// <summary> /// 中序遍历 /// </summary> public void MidOver() { if (this.LeftTree != null) { this.LeftTree.MidOver(); } Console.WriteLine(Root.Data); if (this.RightTree != null) { this.RightTree.MidOver(); } } /// <summary> /// 后序遍历 /// </summary> public void BehindOver() { if (this.LeftTree != null) { this.LeftTree.BehindOver(); } if (this.RightTree != null) { this.RightTree.BehindOver(); } Console.WriteLine(Root.Data); } } }