using System;
using System.Collections.Generic;
using System.Text;
namespace BinaryTree
{
public class Tree<T> where T : IComparable<T>
{
#region 字段
private T data;
private Tree<T> left;
private Tree<T> right;
#endregion
#region 属性
/// <summary>
/// 节点数据
/// </summary>
public T NodeData
{
get { return this.data; }
set { this.data = value; }
}
/// <summary>
/// 左子树
/// </summary>
public Tree<T> LeftTree
{
get { return this.left; }
set { this.left = value; }
}
/// <summary>
/// 右子树
/// </summary>
public Tree<T> RightTree
{
get { return right; }
set { right = value; }
}
#endregion
#region 方法
/// <summary>
/// 自定义构造函数
/// </summary>
/// <param name="nodeValue"></param>
public Tree(T nodeValue)
{
this.data = nodeValue;
this.left = null;
this.right = null;
}
/// <summary>
/// 将新项插入二叉树中
/// </summary>
/// <param name="newItem">新项</param>
public void Insert(T newItem)
{
T currentNodeValue = this.NodeData;
if (currentNodeValue.CompareTo(newItem) > 0)
{
// 在左子树中插入新项
if (this.LeftTree == null)
{
// 使用新项创建新的左子树
this.LeftTree = new Tree<T>(newItem);
}
else
{
// 递归调用Insert方法,将新项插入现有左子树中
this.LeftTree.Insert(newItem);
}
}
else
{
// 在右子树中插入新项
if (this.RightTree == null)
{
// 使用新项创建新的右子树
this.RightTree = new Tree<T>(newItem);
}
else
{
// 递归调用Insert方法,将新项插入现有右子树中
this.RightTree.Insert(newItem);
}
}
}
/// <summary>
/// 中序遍历二叉树
/// </summary>
public void WalkTree()
{
if (this.LeftTree != null)
{
// 遍历左子树
this.LeftTree.WalkTree();
}
Console.WriteLine(this.NodeData.ToString());
if (this.RightTree != null)
{
// 遍历右子树
this.RightTree.WalkTree();
}
}
#endregion
}
}
测试:
using System;
using System.Collections.Generic;
using System.Text;
using BinaryTree;
namespace BinaryTreeTest
{
class Program
{
static void Main(string[] args)
{
Tree<int> tree1 = new Tree<int>(10);
tree1.Insert(5);
tree1.Insert(11);
tree1.Insert(5);
tree1.Insert(-12);
tree1.Insert(15);
tree1.Insert(0);
tree1.Insert(14);
tree1.Insert(-8);
tree1.Insert(10);
tree1.Insert(8);
tree1.Insert(8);
tree1.WalkTree();
Tree<string> tree2 = new Tree<string>("Hello");
tree2.Insert("World");
tree2.Insert("How");
tree2.Insert("Are");
tree2.Insert("You");
tree2.Insert("Today");
tree2.Insert("I");
tree2.Insert("You");
tree2.Insert("Are");
tree2.Insert("Feeling");
tree2.Insert("Well");
tree2.WalkTree();
string[] test = new string[3];
test[0] = "hello";
test[1] = "world";
test[2] = "haha";
Tree<string> temp = BuildTree<string>(test);
temp.WalkTree();
Tree<string> array = BuildTree<string>("hello", "world", "haha");
array.WalkTree();
}
public static Tree<T> BuildTree<T>(params T[] data) where T : IComparable<T>
{
Tree<T> sortTree = new Tree<T>(data[0]);
for (int i = 1; i < data.Length; i++)
{
sortTree.Insert(data[i]);
}
return sortTree;
}
}
}