C# 實現的一個二叉樹類
原文地址 http://www.cnblogs.com/ppchouyou/archive/2008/07/18/1245819.html
昨天用C#寫了一個二叉樹的類,包括如何構造二叉樹的根節點,向二叉樹中插入一個節點順便實現了一下二叉樹的四種遍歷方法:前序,中序,後序,逐層。前三種方法用了遞迴的方式,後一種方法用了一個連結串列來解決中間資料的儲存問題。感覺這個東東確實包含了不少值得回味的東西。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace BinaryTree
{
public class Tree<T> where T:IComparable<T>//where 指定T從IComparable<T>繼承
{
/// <summary>
/// 定義二叉樹
///</summary>
private T data;
private Tree<T> left;
private Tree<T> right;
/// <summary>
/// 建構函式:定義二叉樹的根節點
///</summary>
/// <paramname="nodeValue">二叉樹的根節點</param>
public Tree(T nodeValue)
{
this.data = nodeValue;
this.left = null;
this.right = null;
}
/// <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 this.right; }
set { this.right = value; }
}
/// <summary>
/// 向二叉叔中插入一個節點
/// 儲存思想,凡是小於該結點值的資料全部都在該節點的左子樹中,凡是大於該結點結點值的資料全部在該節點的右子樹中
///</summary>
/// <paramname="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
{
this.LeftTree.Insert(newItem);
}
}
else
{
if (this.RightTree== null)
{
this.RightTree =new Tree<T>(newItem);
}
else
{
this.RightTree.Insert(newItem);
}
}
}
/// <summary>
/// 前序遍歷:先跟節點然後左子樹,右子樹
///</summary>
/// <paramname="root"></param>
public void PreOrderTree(Tree<T> root)
{
if (root != null)
{
Console.Write(root.NodeData);
PreOrderTree(root.LeftTree);
PreOrderTree(root.RightTree);
}
}
/// <summary>
/// 中序遍歷:左子樹,根節點,右子樹可以實現順序輸出
///</summary>
/// <paramname="root"></param>
public void InOrderTree(Tree<T> root)
{
if (root != null)
{
InOrderTree(root.LeftTree);
Console.Write(root.NodeData);
InOrderTree(root.RightTree);
}
}
/// <summary>
/// 後序遍歷:左子樹,右子樹,根節點
///</summary>
/// <paramname="root"></param>
public void PostOrderTree(Tree<T> root)
{
if (root != null)
{
PostOrderTree(root.LeftTree);
PostOrderTree(root.RightTree);
Console.Write(root.NodeData);
}
}
/// <summary>
/// 逐層遍歷:遍歷思想是從根節點開始,訪問一個節點然後將其左右子樹的根節點依次放入連結串列中,然後刪除該節點。
/// 依次遍歷直到連結串列中的元素數量為0即沒有更下一層的節點出現時候為止。
///</summary>
public void WideOrderTree()
{
List<Tree<T>> nodeList = newList<Tree<T>>();
nodeList.Add(this);
Tree<T> temp = null;
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();
}
}
}