public class Tree
{
///
/// 定义二叉树
///
private T data;
private Tree
private Tree
///
/// 构造函数:定义二叉树的根节点
///
/// 二叉树的根节点
public Tree(T nodeValue)
{
this.data = nodeValue;
this.left = null;
this.right = null;
}
///
/// 数据节点属性
///
public T NodeData
{
get { return this.data; }
set { this.data = value; }
}
///
/// 左子树
///
public Tree
{
get { return this.left; }
set { this.left = value; }
}
///
/// 右子树
///
public Tree
{
get { return this.right; }
set { this.right = value; }
}
///
/// 向二叉叔中插入一个节点
/// 存储思想,凡是小于该结点值的数据全部都在该节点的左子树中,凡是大于该结点结点值的数据全部在该节点的右子树中
///
///
public void Insert(T newItem)
{
T currentNodeValue = this.NodeData;
if (currentNodeValue.CompareTo(newItem) > 0)
{
if (this.LeftTree == null)
{
this.LeftTree = new Tree
}
else
{
this.LeftTree.Insert(newItem);
}
}
else
{
if (this.RightTree == null)
{
this.RightTree = new Tree
}
else
{
this.RightTree.Insert(newItem);
}
}
}
///
/// 前序遍历:先跟节点然后左子树,右子树
///
///
public void PreOrderTree(Tree
{
if (root != null)
{
Console.Write(root.NodeData);
PreOrderTree(root.LeftTree);
PreOrderTree(root.RightTree);
}
}
///
/// 中序遍历:左子树,根节点,右子树可以实现顺序输出
///
///
public void InOrderTree(Tree
{
if (root != null)
{
InOrderTree(root.LeftTree);
Console.Write(root.NodeData);
InOrderTree(root.RightTree);
}
}
///
/// 后序遍历:左子树,右子树,根节点
///
///
public void PostOrderTree(Tree
{
if (root != null)
{
PostOrderTree(root.LeftTree);
PostOrderTree(root.RightTree);
Console.Write(root.NodeData);
}
}
///
/// 逐层遍历:遍历思想是从根节点开始,访问一个节点然后将其左右子树的根节点依次放入链表中,然后删除该节点。
/// 依次遍历直到链表中的元素数量为0即没有更下一层的节点出现时候为止。
///
public void WideOrderTree()
{
List
nodeList.Add(this);
Tree
while (nodeList.Count > 0)
{
Console.Write(nodeList[0].NodeData);
temp = nodeList[0];
nodeList.Remove(nodeList[0]);
if (temp.LeftTree != null)
{
nodeList.Add(temp.LeftTree);
}
if (temp.RightTree != null)
{
nodeList.Add(temp.RightTree);
}
}
Console.WriteLine();
}
}