编程学C#(3):动态模拟创建二叉树程序
(2014-5-14)编制的动态模拟创建二叉树程序,学习VS2010 C#的应用。
一、 主要内容:
1. C#中如何建立二叉树链表;
2. 二叉树先序遍历与图形显示的应用;
程序运行示例如下:
二、 设计实现:
(一)、C#中如何建立二叉树链表的实现
1. 建立二叉树链表类
public class TreeNode<T>
{
private T data;
private TreeNode<T>lChild;//左子节点
private TreeNode<T>rChild;//右子节点
public TreeNode(T data)
{
this.data = data;
lChild = null;
rChild = null;
}
public T Data
{
get { return this.data; }
set { this.data = value; }
}
public TreeNode<T>LChild
{
get { return this.lChild; }
set { this.lChild = value; }
}
public TreeNode<T>RChild
{
get { return this.rChild; }
set { this.rChild = value; }
}
}
2. 构建二叉树类,建立生成二叉树方法
由于C#中没有指针,建立链接表的方法使用new新建实例:
public class BinaryTree
{
private Stringorder,inorder;
private int i=0,j=0;
private char[]inStr=new char[40];
public TreeNode<char> root;
public BinaryTree(String s)
{
order=s;
if(order.Length>0)
root=creattree();
}
public TreeNode<char> creattree()
{
TreeNode<char>p=null;
if(i < order.Length)
{
charstr = order[i];
i++;
if(str != '@')
{
p = new TreeNode<char>(str);
p.LChild=creattree();
p.RChild=creattree();
}
}
return p;
}
}
(二)、二叉树先序遍历与图形显示的应用
函数PrintTree()是递归定义的,它通过先序遍历二叉树T,将二叉树先序创建过程显示在窗体上。先访问根结点,画圆圈及字符;接着递归遍历左子树,画左子树连接线;递归遍历右子树,画右子树连接线。
public bool PrintTree(TreeNode<char> T, int x, int y)
{
stringSignchar;
if(T != null)
{
{
Signchar =T.Data.ToString();
Penp = new Pen(Color.Black, 1);
g.DrawEllipse(p, x, y, 20,20);
FontdrawFont = new Font("Arial", 16);
SolidBrushdrawBrush = new SolidBrush(Color.Red);
PointFdrawPoint = new PointF(x, y );
g.DrawString(Signchar,drawFont, drawBrush, drawPoint);
System.Threading.Thread.Sleep(1000); //1second
}
if(PrintTree(T.LChild, x - (240 - y), y + 30))
{
Penp = new Pen(Color.Blue, 2);
g.DrawLine(p, x, y+10, x -(240 - y)+20, y + 40);
}
if(PrintTree(T.RChild, x + (240 - y), y + 30))
{
Penp = new Pen(Color.DarkRed, 2);
g.DrawLine(p, x+20, y+10, x+ (240 - y)+2, y + 40);
}
returntrue;
}
returnfalse;
}