加入收藏 | 设为首页 | 会员中心 | 我要投稿 焦作站长网 (https://www.0391zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 安全 > 正文

算法系列15天速成 第六天 五大经典查找【下】

发布时间:2020-03-14 19:09:48 所属栏目:安全 来源:站长网
导读:大家是否感觉到,树在数据结构中大行其道,什么领域都要沾一沾,碰一碰

Console.WriteLine("删除根节点 50, n中序遍历后:");
            //删除根节点
            DeleteBST(ref bsTree, 50);

LDR_BST(bsTree);

}

///<summary>
/// 定义一个二叉排序树结构
///</summary>
        public class BSTree
        {
            public int data;
            public BSTree left;
            public BSTree right;
        }

///<summary>
/// 二叉排序树的插入操作
///</summary>
///<param>排序树</param>
///<param>插入数</param>
///<param>是否执行了if语句</param>
        static void InsertBST(BSTree bsTree, int key, ref bool isExcute)
        {
            if (bsTree == null)
                return;

//如果父节点大于key,则遍历左子树
            if (bsTree.data > key)
                InsertBST(bsTree.left, key, ref isExcute);
            else
                InsertBST(bsTree.right, key, ref isExcute);

if (!isExcute)
            {
                //构建当前节点
                BSTree current = new BSTree()
                  {
                      data = key,
                      left = null,
                      right = null
                  };

//插入到父节点的当前元素
                if (bsTree.data > key)
                    bsTree.left = current;
                else
                    bsTree.right = current;

isExcute = true;
            }

}

///<summary>
/// 创建二叉排序树
///</summary>
///<param></param>
        static BSTree CreateBST(List<int> list)
        {
            //构建BST中的根节点
            BSTree bsTree = new BSTree()
            {
                data = list[0],
                left = null,
                right = null
            };

for (int i = 1; i < list.Count; i++)
            {
                bool isExcute = false;
                InsertBST(bsTree, list[i], ref isExcute);
            }
            return bsTree;
        }

///<summary>
/// 在排序二叉树中搜索指定节点
///</summary>
///<param></param>
///<param></param>
///<returns></returns>
        static bool SearchBST(BSTree bsTree, int key)
        {
            //如果bsTree为空,说明已经遍历到头了
            if (bsTree == null)
                return false;

if (bsTree.data == key)
                return true;

(编辑:焦作站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读