在上面的Tree<T>类中添加了三个私有变量,只要有二叉树概念,其含义自明,不多赘述。接下来,我们在类中添加两个方法Insert和WalkTree,分别用于插入结点和遍历二叉树。相应代码如下:
//此方法在二叉树中插入一个值为T的结点。
//注意,因为用户可以使用构造器在树中插入初始的根结点,所以在此方法中
//我们树是非空的。
public void Insert(T newItem)
...{
T currentNodeValue = this.NodeData;
// CompareTo含义上面已作解释,用于判断当前节点值是否大于新项
if (currentNodeValue.CompareTo(newItem) > 0)
...{
if (this.LeftTree == null)
...{
this.LeftTree = new Tree<T>(newItem);
}
else
...{
this.LeftTree.Insert(newItem);
}
}
else
...{
if (this.RightTree == null)
...{
this.RightTree = new Tree<T>(newItem);
}
else
...{
this.RightTree.Insert(newItem);
}
}
}
//此方法负责遍历二叉树-把结点值转换为字符串,并输出到控制台
public void WalkTree()
...{
if (this.LeftTree != null) //判断左结点是否为空
...{
this.LeftTree.WalkTree();//非空,则递归遍历左子树
}
Console.WriteLine(this.NodeData.ToString());//输出到控制台
if (this.RightTree != null) //判断右结点是否为空
...{
this.RightTree.WalkTree();//非空,则递归遍历右子树
}
}
四、 测试Tree<T>类
为了测试上面库中的二叉树类,选择“文件→新建→添加项目”,选用“控制台应用程序”模板来添加一个新项目,并将项目命名为BinaryTreeTest。
在解决方案资源管理器中,选择BinaryTreeTest项目并将之设置为启动项目。
选择“项目→添加引用”。单击“项目”标签,单击BinaryTree项目,并确定。
最后,我们在Main方法中加入如下语句进行测试:
static void Main(string[] args) { Tree<int> tree1 = new Tree<int>(10); tree1.Insert(9); tree1.Insert(6); tree1.Insert(5); tree1.Insert(-12); tree1.Insert(177); tree1.Insert(0); tree1.Insert(9); tree1.Insert(9); tree1.WalkTree(); Tree<string> tree2 = new Tree<string>("Hello"); tree2.Insert("World"); tree2.Insert("How"); tree2.Insert("Old"); tree2.Insert("Are"); tree2.Insert("You"); tree2.WalkTree(); Console.Read(); }
运行结果如下图所示:

五、 小结
“泛型”概念在增加类型安全的同时,也大大提高了软件的模块化开发。在本文中,我们基于泛型概念创建了一棵简单的二叉树。当然,在实践中还有待于大量的“美化”。