C#資料結構-二叉樹-順序儲存結構

溫暖如太陽發表於2020-12-05

什麼是二叉樹:每個樹的節點只有兩個子樹的樹形結構。

為什麼使用順序儲存結構:使用陣列存放滿二叉樹的各結點非常方便,可以根據一個結點的索引號很容易地推算出它的雙親、孩子、兄弟等結點的編號,從而對這些結點進行訪問,這是一種儲存二叉滿二叉樹或完全二叉樹的最簡單、最省空間的做法。

 /// <summary>
/// 順序儲存二叉樹
/// </summary>
public class SequentialStorageBinaryTree<T>
{
    /// <summary>
    /// 用於儲存節點的陣列
    /// </summary>
    private T[] data;
    /// <summary>
    /// 節點數
    /// </summary>
    private int count;

    public SequentialStorageBinaryTree(T[] arr = null)
    {
        if (arr == null)
            data = new T[0];
        else
            data = arr;
        count = data.Length;
    }

    /// <summary>
    /// 增加
    /// </summary>
    /// <param name="item"></param>
    public bool Add(T item)
    {
        List<T> list = data.ToList<T>();
        list.Add(item);
        data = list.ToArray();
        count = data.Length;
        return true;
    }
}

通過陣列儲存結構為:

 

1、層次遍歷

/// <summary>
/// 層次遍歷
/// </summary>
public void LevelTraversal()
{
    for (int i = 0; i < count; i++)
    {
        Console.Write(data[i] + " ");
    }
}

 

2、先序遍歷

/// <summary>
/// 先序遍歷
/// </summary>
/// <param name="index"></param>
public void PreorderTraversal(int index =0)
{
    //遞迴的終止條件
    if (index >= count || index <0)
        return;
    int number = index + 1;
    Console.Write(data[index] + " ");
    int leftIndex = number * 2;//做節點
    int rightIndex = number * 2 + 1;
    PreorderTraversal(leftIndex - 1);
    PreorderTraversal(rightIndex - 1);
}

 

 3、中序遍歷

/// <summary>
/// 中序遍歷
/// </summary>
/// <param name="index"></param>
public void MiddlePrefaceTraversal(int index = 0)
{
    //遞迴的終止條件
    if (index >= count || index < 0)
        return;
    int number = index + 1;
    
    int leftIndex = number * 2;//做節點
    int rightIndex = number * 2 + 1;
    MiddlePrefaceTraversal(leftIndex - 1);
    Console.Write(data[index] + " ");
    MiddlePrefaceTraversal(rightIndex - 1);
}

 

 

4、後續遍歷

/// <summary>
/// 後序遍歷
/// </summary>
/// <param name="index"></param>
public void AfterwordTraversal(int index = 0)
{
    //遞迴的終止條件
    if (index >= count || index < 0)
        return;
    int number = index + 1;
    int leftIndex = number * 2;//做節點
    int rightIndex = number * 2 + 1;
    AfterwordTraversal(leftIndex - 1);
    AfterwordTraversal(rightIndex - 1);
    Console.Write(data[index] + " ");
}

 

 現在我們測試下:

SequentialStorageBinaryTree<string> bTree = new SequentialStorageBinaryTree<string>();
bTree.Add("A");
bTree.Add("B");
bTree.Add("C");
bTree.Add("D");
bTree.Add("E");
bTree.Add("F");
bTree.Add("G");

//先序遍歷
Console.Write("先序遍歷:");
bTree.PreorderTraversal();
Console.WriteLine();

//中序遍歷
Console.Write("中序遍歷:");
bTree.MiddlePrefaceTraversal();
Console.WriteLine();

//中序遍歷
Console.Write("後序遍歷:");
bTree.AfterwordTraversal();
Console.WriteLine();

//層次遍歷
Console.Write("層次遍歷:");
bTree.LevelTraversal();
Console.ReadKey();

輸出:

 

 


 

 

 

 

相關文章