關於c#二叉樹的實現

來源:互聯網
上載者:User

本篇純屬娛樂,源於整理代碼,發現還曾實現過遍曆二叉樹。

雖然.NET/C#中的各種集合類已經實現了最優的排序設計,但瞭解基本的演算法實現有助於軟體開發中的各種權衡和選擇。
比如,如果你實現過B+樹排序和尋找,並將樹節點序列化至二進位檔案塊,則你應該已經瞭解了各種資料庫索引的基本設計。

什麼是二叉樹?
http://en.wikipedia.org/wiki/Binary_tree

二叉樹節點類定義

複製代碼 代碼如下:View Code
/// <summary>
/// 二叉樹節點
/// </summary>
/// <typeparam name="T">The item type</typeparam>
public class BinaryTreeNode<T>
{
#region Constructors

/// <summary>
/// 二叉樹節點
/// </summary>
public BinaryTreeNode()
{
}

/// <summary>
/// 二叉樹節點
/// </summary>
/// <param name="value">節點中的值</param>
public BinaryTreeNode(T value)
{
this.Value = value;
}

/// <summary>
/// 二叉樹節點
/// </summary>
/// <param name="value">節點中的值</param>
/// <param name="parent">節點的父節點</param>
public BinaryTreeNode(T value, BinaryTreeNode<T> parent)
{
this.Value = value;
this.Parent = parent;
}

/// <summary>
/// 二叉樹節點
/// </summary>
/// <param name="value">節點中的值</param>
/// <param name="parent">節點的父節點</param>
/// <param name="left">節點的左節點</param>
/// <param name="right">節點的右節點</param>
public BinaryTreeNode(T value,
BinaryTreeNode<T> parent,
BinaryTreeNode<T> left,
BinaryTreeNode<T> right)
{
this.Value = value;
this.Right = right;
this.Left = left;
this.Parent = parent;
}

#endregion

#region Properties

/// <summary>
/// 節點值
/// </summary>
public T Value { get; set; }

/// <summary>
/// 父節點
/// </summary>
public BinaryTreeNode<T> Parent { get; set; }

/// <summary>
/// 左節點
/// </summary>
public BinaryTreeNode<T> Left { get; set; }

/// <summary>
/// 右節點
/// </summary>
public BinaryTreeNode<T> Right { get; set; }

/// <summary>
/// 是否為根節點
/// </summary>
public bool IsRoot { get { return Parent == null; } }

/// <summary>
/// 是否為葉子節點
/// </summary>
public bool IsLeaf { get { return Left == null && Right == null; } }

/// <summary>
/// 是否為可訪問的
/// </summary>
internal bool Visited { get; set; }

#endregion

#region Public Overridden Functions

/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return Value.ToString();
}

#endregion
}

二叉樹類實現複製代碼 代碼如下:View Code
/// <summary>
/// 二叉樹
/// </summary>
/// <typeparam name="T">二叉樹中節點內容類型</typeparam>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public class BinaryTree<T> : ICollection<T>, IEnumerable<T> where T : IComparable<T>
{
#region Constructor

/// <summary>
/// 二叉樹
/// </summary>
public BinaryTree()
{
NumberOfNodes = 0;
}

/// <summary>
/// 二叉樹
/// </summary>
/// <param name="root">二叉樹根節點</param>
public BinaryTree(BinaryTreeNode<T> root)
: this()
{
this.Root = root;
}

#endregion

#region Properties

/// <summary>
/// 樹的根節點
/// </summary>
public BinaryTreeNode<T> Root { get; set; }

/// <summary>
/// 樹中節點的數量
/// </summary>
protected int NumberOfNodes { get; set; }

/// <summary>
/// 樹是否為空白
/// </summary>
public bool IsEmpty { get { return Root == null; } }

/// <summary>
/// 擷取樹中節點的最小值
/// </summary>
public T MinValue
{
get
{
if (IsEmpty)
return default(T);

BinaryTreeNode<T> minNode = Root;
while (minNode.Left != null)
minNode = minNode.Left;

return minNode.Value;
}
}

/// <summary>
/// 擷取樹中節點的最大值
/// </summary>
public T MaxValue
{
get
{
if (IsEmpty)
return default(T);

BinaryTreeNode<T> maxNode = Root;
while (maxNode.Right != null)
maxNode = maxNode.Right;

return maxNode.Value;
}
}

#endregion

#region IEnumerable<T> Members

/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"></see>
/// that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
foreach (BinaryTreeNode<T> node in Traverse(Root))
{
yield return node.Value;
}
}

#endregion

#region IEnumerable Members

/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/>
/// object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
foreach (BinaryTreeNode<T> node in Traverse(Root))
{
yield return node.Value;
}
}

#endregion

#region ICollection<T> Members

/// <summary>
/// 新增節點
/// </summary>
/// <param name="item">The object to add to the
/// <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
/// <exception cref="T:System.NotSupportedException">The
/// <see cref="T:System.Collections.Generic.ICollection`1"></see>
/// is read-only.</exception>
public void Add(T item)
{
if (Root == null)
{
Root = new BinaryTreeNode<T>(item);
++NumberOfNodes;
}
else
{
Insert(item);
}
}

/// <summary>
/// 清除樹
/// </summary>
public void Clear()
{
Root = null;
}

/// <summary>
/// 樹中是否包含此節點
/// </summary>
/// <param name="item">The object to locate in the
/// <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
/// <returns>
/// true if item is found in the
/// <see cref="T:System.Collections.Generic.ICollection`1"></see>; otherwise, false.
/// </returns>
public bool Contains(T item)
{
if (IsEmpty)
return false;

BinaryTreeNode<T> currentNode = Root;
while (currentNode != null)
{
int comparedValue = currentNode.Value.CompareTo(item);
if (comparedValue == 0)
return true;
else if (comparedValue < 0)
currentNode = currentNode.Left;
else
currentNode = currentNode.Right;
}

return false;
}

/// <summary>
/// 將樹中節點拷貝至目標數組
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(T[] array, int arrayIndex)
{
T[] tempArray = new T[NumberOfNodes];
int counter = 0;
foreach (T value in this)
{
tempArray[counter] = value;
++counter;
}
Array.Copy(tempArray, 0, array, arrayIndex, Count);
}

/// <summary>
/// 樹中節點的數量
/// </summary>
public int Count
{
get { return NumberOfNodes; }
}

/// <summary>
/// 樹是否為唯讀
/// </summary>
public bool IsReadOnly
{
get { return false; }
}

/// <summary>
/// 移除節點
/// </summary>
/// <param name="item">節點值</param>
/// <returns>是否移除成功</returns>
public bool Remove(T item)
{
BinaryTreeNode<T> node = Find(item);
if (node == null)
return false;

List<T> values = new List<T>();
foreach (BinaryTreeNode<T> l in Traverse(node.Left))
{
values.Add(l.Value);
}
foreach (BinaryTreeNode<T> r in Traverse(node.Right))
{
values.Add(r.Value);
}

if (node.Parent.Left == node)
{
node.Parent.Left = null;
}
else
{
node.Parent.Right = null;
}

node.Parent = null;

foreach (T v in values)
{
this.Add(v);
}

return true;
}

#endregion

#region Private Functions

/// <summary>
/// 尋找指定值的節點
/// </summary>
/// <param name="value">指定值</param>
/// <returns>
/// 指定值的節點
/// </returns>
protected BinaryTreeNode<T> Find(T value)
{
foreach (BinaryTreeNode<T> node in Traverse(Root))
if (node.Value.Equals(value))
return node;
return null;
}

/// <summary>
/// 遍曆樹
/// </summary>
/// <param name="node">遍曆搜尋的起始節點</param>
/// <returns>
/// The individual items from the tree
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
protected IEnumerable<BinaryTreeNode<T>> Traverse(BinaryTreeNode<T> node)
{
// 遍曆左子樹
if (node.Left != null)
{
foreach (BinaryTreeNode<T> left in Traverse(node.Left))
yield return left;
}

// 中序遍曆二叉樹, 順序是 左子樹,根,右子樹
yield return node;

// 遍曆右子樹
if (node.Right != null)
{
foreach (BinaryTreeNode<T> right in Traverse(node.Right))
yield return right;
}
}

/// <summary>
/// 插入節點
/// </summary>
/// <param name="value">插入的節點值</param>
protected void Insert(T value)
{
// 從根節點開始比較
BinaryTreeNode<T> currentNode = Root;

while (true)
{
if (currentNode == null)
throw new InvalidProgramException("The current tree node cannot be null.");

// 比較當前節點與新節點的值
int comparedValue = currentNode.Value.CompareTo(value);
if (comparedValue < 0)
{
// 當前節點值小於新節點值
if (currentNode.Left == null)
{
currentNode.Left = new BinaryTreeNode<T>(value, currentNode);
++NumberOfNodes;
return;
}
else
{
currentNode = currentNode.Left;
}
}
else if (comparedValue > 0)
{
// 當前節點值大於新節點值
if (currentNode.Right == null)
{
currentNode.Right = new BinaryTreeNode<T>(value, currentNode);
++NumberOfNodes;
return;
}
else
{
currentNode = currentNode.Right;
}
}
else
{
// 當前節點值等於新節點值
currentNode = currentNode.Right;
}
}
}

#endregion
}

使用舉例複製代碼 代碼如下:class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;

BinaryTree<string> tree = new BinaryTree<string>();
tree.Add("Dennis");
tree.Add("Gao");
tree.Add("Is");
tree.Add("A");
tree.Add("C#");
tree.Add("Programmer");

Console.WriteLine("Root Node Is : " + tree.Root.ToString());
Console.WriteLine();

foreach (var node in tree)
{
Console.WriteLine(node);
}

Console.ReadKey();
}
}

中序遍曆二叉樹

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.