二叉树
Posted 游戏鼻祖
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树相关的知识,希望对你有一定的参考价值。
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace MyTree { class Tree<T> where T:IComparable<T> //该接口用于处理泛型的大小比较 { private T Data; //数据 private int count; //数据的次数 private Tree<T> LTree;//左子树 private Tree<T> RTree;//右子树 public Tree(T value) { Data = value; count = 1; LTree = null; RTree = null; } public void Insert(T newTree) { T currentNodeValue = this.Data; if(currentNodeValue.CompareTo(newTree)>0) { if(this.LTree==null) { this.LTree = new Tree<T>(newTree); } else { this.LTree.Insert(newTree); } } else if (currentNodeValue.CompareTo(newTree)<0) { if(this.RTree==null) { this.RTree = new Tree<T>(newTree); } else { this.RTree.Insert(newTree); } } else { this.count++; } } /// <summary> /// 中序遍历 /// </summary> public void midOrder() { if(this.LTree!=null) { this.LTree.midOrder(); } Console.WriteLine(this.Data+","+this.count); if(this.RTree!=null) { this.RTree.midOrder(); } } /// <summary> /// 先序遍历 /// </summary> public void firstOrder() { Console.WriteLine(this.Data + "," + this.count); if (this.LTree != null) { this.LTree.firstOrder(); } if (this.RTree != null) { this.RTree.firstOrder(); } } /// <summary> /// 后序遍历 /// </summary> public void lastOrder() { Console.WriteLine(this.Data + "," + this.count); if (this.LTree != null) { this.LTree.lastOrder(); } if (this.RTree != null) { this.RTree.lastOrder(); } } } }
using System; namespace MyTree { class Program { static void Main(string[] args) { Tree<int> tree = new Tree<int>(10); tree.Insert(2); tree.Insert(4); tree.Insert(9); tree.Insert(15); Console.WriteLine("先序遍历"); tree.firstOrder(); Console.WriteLine(); Console.WriteLine("后序遍历"); tree.lastOrder(); Console.WriteLine(); Console.WriteLine("中序遍历"); tree.midOrder(); Console.ReadKey(); } } }
以上是关于二叉树的主要内容,如果未能解决你的问题,请参考以下文章