如题,代码如下:
class BinaryTree
{
/// <summary>
/// 创建二叉树,并返回根结点
/// </summary>
/// <returns></returns>
public static nodes<string> BinTree()
{
nodes<string>[] list = new nodes<string>[8];
//创建结点
list[0] = new nodes<string>("A");
list[1] = new nodes<string>("B");
list[2] = new nodes<string>("C");
list[3] = new nodes<string>("D");
list[4] = new nodes<string>("E");
list[5] = new nodes<string>("F");
list[6] = new nodes<string>("G");
list[7] = new nodes<string>("H");
//利用层次方式创建二叉树
list[0].LNode = list[1];
list[0].RNode = list[2];
list[1].RNode = list[3];
list[2].LNode = list[4];
list[2].RNode = list[5];
list[3].LNode = list[6];
list[3].RNode = list[7];
return list[0];
}
/// <summary>
/// 先序遍历
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rootNode"></param>
public static void PreOrder<T>(nodes<T> rootNode)
{
if (rootNode != null)
{
Console.Write(rootNode.Data);
PreOrder<T>(rootNode.LNode);
PreOrder<T>(rootNode.RNode);
}
}
/// <summary>
/// 中序遍历
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rootNode"></param>
public static void MidOrder<T>(nodes<T> rootNode)
{
if (rootNode != null)
{
MidOrder<T>(rootNode.LNode);
Console.Write(rootNode.Data);
MidOrder<T>(rootNode.RNode);
}
}
/// <summary>
/// 后序遍历
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rootNode"></param>
public static void EndOrder<T>(nodes<T> rootNode)
{
if (rootNode != null)
{
EndOrder<T>(rootNode.LNode);
EndOrder<T>(rootNode.RNode);
Console.Write(rootNode.Data);
}
}
/// <summary>
/// 层次遍历
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rootNode"></param>
public static void LayOrder<T>(nodes<T> rootNode)
{
nodes<T>[] list = new nodes<T>[20];
int front = -1;
int rear = -1;
if (rootNode != null)
{
rear++;
list[rear] = rootNode;
}
while (front != rear)
{
front++;
rootNode = list[front];
Console.Write(rootNode.Data);
if (rootNode.LNode != null)
{
rear++;
list[rear] = rootNode.LNode;
}
if (rootNode.RNode != null)
{
rear++;
list[rear] = rootNode.RNode;
}
}
}
/// <summary>
/// 交换
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rootNode"></param>
public static void SortTree<T>(nodes<T> rootNode)
{
if (rootNode.LNode != null)
SortTree<T>(rootNode.LNode);
if (rootNode != null)
{
nodes<T> node = new nodes<T>();
if (rootNode.LNode != null)
{
node = rootNode.LNode;
}
if (rootNode.RNode != null)
{
rootNode.LNode = rootNode.RNode;
}
if (node != null)
{
rootNode.RNode = node;
}
}
if (rootNode.LNode != null)
SortTree<T>(rootNode.LNode);
}
}
class nodes<T>
{
public nodes() { }
public nodes(T d)
{
this.data = d;
}
T data;
nodes<T> lNode, rNode, pNode;
internal nodes<T> PNode
{
get { return pNode; }
set { pNode = value; }
}
internal nodes<T> RNode
{
get { return rNode; }
set { rNode = value; }
}
internal nodes<T> LNode
{
get { return lNode; }
set { lNode = value; }
}
public T Data
{
get { return data; }
set { data = value; }
}
}