BNode类:
namespace binarysorttree.Tree {
public class BNode<T> {
public T data;
public BNode<T> left;
public BNode<T> right;
public BNode(T data, BNode<T> left=null, BNode<T> right=null) {
this.data = data;
this.left = left;
this.right = right;
}
}
}
BTree类:
using System;
namespace binarysorttree.Tree {
public class BTree<T> {
public BNode<T> root;
public void preOrder() {
Console.Write("先根遍历二叉树:");
preOrder(this.root);
Console.WriteLine();
}
public void preOrder(BNode<T> p) {
if(p!=null) {
Console.Write(p.data+" ");
preOrder(p.left);
preOrder(p.right);
}
}
public void inOrder() {
Console.Write("中根遍历二叉树:");
inOrder(this.root);
Console.WriteLine();
}
public void inOrder(BNode<T> p) {
if(p!=null) {
inOrder(p.left);
Console.Write(p.data+" ");
inOrder(p.right);
}
}
public void postOrder() {
Console.Write("后根遍历二叉树:");
postOrder(this.root);
Console.WriteLine();
}
public void postOrder(BNode<T> p) {
if(p!=null) {
postOrder(p.left);
postOrder(p.right);
Console.Write(p.data+" ");
}
}
}
}
BinarySortTree类:
using System;
namespace binarysorttree.Tree {
public class BinarySortTree<T> : BTree<T> where T:struct, IComparable<T>{
public BinarySortTree():base() {
}
public BNode<T> search(T value) {
BNode<T> p = this.root;
while(p!=null && p.data.CompareTo(value)!=0) {
if(value.CompareTo(p.data)<0) {
p=p.left;
}else {
p=p.right;
}
}
return p;
}
}
}
主程序类:
using System;
using binarysorttree.Tree;
namespace binarysorttree
{
class Program
{
static void make(ref BinarySortTree<int> sortTree)
{
BNode<int> node12 = new BNode<int>(12, new BNode<int>(6), null);
BNode<int> node18 = new BNode<int>(18, node12, new BNode<int>(36));
BNode<int> node76 = new BNode<int>(76, null, new BNode<int>(81));
BNode<int> node87 = new BNode<int>(87, node76, new BNode<int>(99));
BNode<int> node66 = new BNode<int>(66, new BNode<int>(57), node87);
BNode<int> node54 = new BNode<int>(54, node18, node66);
sortTree.root = node54;
}
static void Main(string[] args)
{
BinarySortTree<int> bTree = new BinarySortTree<int>();
Program.make(ref bTree);
bTree.preOrder();
BNode<int> node36 = bTree.search(36);
if (node36 != null)
{
Console.WriteLine($"node36的数据为: {node36.data}");
}
}
}
}
程序输出如下,