二叉排序樹查找


構造一棵二叉排序樹的目的,其實並不是為了排序,而是為了提高查找和插入刪除的效率。

那么什么是二叉排序樹呢?二叉排序樹具有以下幾個特點。

1,若根節點有左子樹,則左子樹的所有節點都比根節點小。

2,若根節點有右子樹,則右子樹的所有節點都比根節點大。

3,根節點的左,右子樹也分別為二叉排序樹。

下面是二叉排序樹的圖示,通過圖可以加深對二叉排序樹的理解。

ds38

下面是二叉排序樹常見的操作及思路。

1,插入節點

思路:比如我們要插入數字20到這棵二叉排序樹中。那么步驟如下:

1) 首先將20與根節點進行比較,發現比根節點小,所以繼續與根節點的左子樹30比較。

2) 發現20比30也要小,所以繼續與30的左子樹10進行比較。

3) 發現20比10要大,所以就將20插入到10的右子樹中。

此時二叉排序樹效果如圖:

ds38

2,查找節點

比如我們要查找節點10,那么思路如下:

1) 還是一樣,首先將10與根節點50進行比較大小,發現比根節點要小,所以繼續與根節點的左子樹30進行比較。

2) 發現10比左子樹30要小,所以繼續與30的左子樹10進行比較。

3) 發現兩值相等,即查找成功,返回10的位置。

過程與插入相同,這里就不貼圖了。

3,刪除節點

刪除節點的情況相對復雜,主要分以下三種情形:

1) 刪除的是葉節點(即沒有孩子節點的)。比如20,刪除它不會破壞原來樹的結構,最簡單。如圖所示。

ds38

2) 刪除的是單孩子節點。比如90,刪除它后需要將它的孩子節點與自己的父節點相連。情形比第一種復雜一些。

ds38

3) 刪除的是有左右孩子的節點。比如根節點50,這里有一個問題就是刪除它后將誰做為根節點的問題?利用二叉樹的中序遍歷,就是右節點的左子樹的最左孩子

ds38

分析完了,有了思路之后,下面就開始寫代碼來實現這些功能了。

C#版:

復制代碼
namespace DS.BLL
{
    /// <summary>
    /// Description:二叉排序樹的常見操作
    /// Author:McgradyLu
    /// Time:8/24/2013 4:12:18 PM
    /// </summary>
    public class BSTreeBLL
    {
        /// <summary>
        /// 創建二叉排序樹
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static BSTree Create(List<int> list)
        { 
            //創建根節點
            BSTree bsTree = new BSTree()
            { 
                Data=list[0],
                Left=null,
                Right=null
            };

            //將list中的節點一個一個地插入到二叉排序樹中
            for (int i = 1; i < list.Count; i++) //注意這里從1開始,因為0位置上元素已經給了根節點
            {
                bool isExcute = false;
                Insert(bsTree, list[i], ref isExcute);
            }
            return bsTree;
        }

        /// <summary>
        /// 插入節點
        /// </summary>
        /// <param name="bsTree">二叉排序樹</param>
        /// <param name="key">待插入值</param>
        /// <param name="isExcute">是否執行了if語句(節點是否插入)</param>
        public static void Insert(BSTree bsTree, int key, ref bool isExcute)
        {
            if (bsTree == null) return;

            //如果小於根節點,遍歷左子樹,否則遍歷右子樹(找到當前要插入節點的父節點)
            if (key < bsTree.Data) Insert(bsTree.Left, key, ref isExcute);
            else Insert(bsTree.Right, key, ref isExcute);

            if (!isExcute)
            {
                //創建當前節點
                BSTree current = new BSTree() { 
                    Data=key,
                    Left=null,
                    Right=null
                };

                //插入到父節點中
                if (key < bsTree.Data) bsTree.Left = current;
                else bsTree.Right = current;
                isExcute = true;
            }
        }

        /// <summary>
        /// 中序遍歷
        /// </summary>
        /// <param name="bsTree"></param>
        public static void LDR(BSTree bsTree)
        {
            if (bsTree != null)
            {
                //遍歷左子樹
                LDR(bsTree.Left);

                //輸出節點數據
                Console.Write(bsTree.Data+" ");

                //遍歷右子樹
                LDR(bsTree.Right);
            }
        }

        /// <summary>
        /// 查找節點
        /// </summary>
        /// <param name="bsTree">待查找的二叉排序樹</param>
        /// <param name="key"></param>
        /// <returns>true表示查找成功,false表示查找失敗</returns>
        public static bool Search(BSTree bsTree, int key)
        {
            //遍歷完沒有找到,查找失敗
            if (bsTree == null) return false;

            //要查找的元素為當前節點,查找成功
            if (key == bsTree.Data) return true;

            //繼續去當前節點的左子樹中查找,否則去當前節點的右子樹中查找
            if (key < bsTree.Data) return Search(bsTree.Left, key);
            else return Search(bsTree.Right,key);
        }

        /// <summary>
        /// 刪除節點
        /// </summary>
        /// <param name="bsTree"></param>
        /// <param name="key"></param>
        public static void Delete(ref BSTree bsTree, int key)
        {
            //空樹
            if (bsTree == null) return;

            //判斷是否是要刪除的節點
            if (key == bsTree.Data)
            { 
                //第一種情況:葉子節點(沒有孩子節點)
                if (bsTree.Left == null && bsTree.Right == null)
                {
                    bsTree = null;
                    return;
                }

                //第二種情況:僅有左子樹
                if (bsTree.Left != null && bsTree.Right == null)
                {
                    bsTree = bsTree.Left;
                    return;
                }

                //第三種情況:僅有右子樹
                if (bsTree.Left == null && bsTree.Right != null)
                {
                    bsTree = bsTree.Right;
                    return;
                }

                //第四種情況:有左,右子樹
                if (bsTree.Left != null && bsTree.Right != null)
                { 
                    //利用中序遍歷找到右節點的左子樹的最左孩子
                    var node = bsTree.Right;
                    while (node.Left != null)
                    {
                        node = node.Left;
                    }

                    node.Left = bsTree.Left;
                    if (node.Right == null)
                    {
                        Delete(ref bsTree,node.Data);
                        node.Right = bsTree.Right;
                    }
                    bsTree = node;
                }
            }

            //遍歷找到要刪除的節點
            if (key < bsTree.Data)
            {
                Delete(ref bsTree.Left, key);
            }
            else
            {
                Delete(ref bsTree.Right, key);
            }
        }
    }

    /// <summary>
    /// 封裝二叉排序樹結構
    /// </summary>
    public class BSTree
    {
        public int Data;

        public BSTree Left;

        public BSTree Right;
    }
}

namespace BSTSearch.CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int> { 50,30,70,10,40,90,80};

            Console.WriteLine("***************創建二叉排序樹***************");
            BSTree bsTree = BSTreeBLL.Create(list);
            Console.Write("中序遍歷的原始數據:\n");
            BSTreeBLL.LDR(bsTree);

            Console.WriteLine("\n********************查找節點********************");
            Console.WriteLine("元素40是否在樹中:{0}",BSTreeBLL.Search(bsTree,40));

            Console.WriteLine("\n********************插入節點********************");
            Console.WriteLine("將元素20插入到樹中");
            bool isExcute=false;
            BSTreeBLL.Insert(bsTree,20,ref isExcute);
            Console.Write("中序遍歷后:\n");
            BSTreeBLL.LDR(bsTree);

            Console.WriteLine("\n********************刪除節點1********************");
            Console.WriteLine("刪除葉子節點20,\n中序遍歷后:\n");
            BSTreeBLL.Delete(ref bsTree,20);
            BSTreeBLL.LDR(bsTree);

            Console.WriteLine("\n********************刪除節點2********************");
            Console.WriteLine("刪除單孩子節點90,\n中序遍歷后:\n");
            BSTreeBLL.Delete(ref bsTree, 90);
            BSTreeBLL.LDR(bsTree);

            Console.WriteLine("\n********************刪除節點2********************");
            Console.WriteLine("刪除根節點50,\n中序遍歷后:\n");
            BSTreeBLL.Delete(ref bsTree, 50);
            BSTreeBLL.LDR(bsTree);

            Console.ReadKey();
        }
    }
}
復制代碼

程序輸出結果如圖:

ds39


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM