C/C++,树算法——二叉树的插入(Insert)算法之源程序

1 文本格式

#include<iostream>
using namespace std;

// A BTree node
class BTreeNode
{
    int* keys; // An array of keys
    int t;     // Minimum degree (defines the range for number of keys)
    BTreeNode** C; // An array of child pointers
    int n;     // Current number of keys
    bool leaf; // Is true when node is leaf. Otherwise false
public:
    BTreeNode(int _t, bool _leaf); // Constructor

    // A utility function to insert a new key in the subtree rooted with
    // this node. The assumption is, the node must be non-full when this
    // function is called
    void insertNonFull(int k);

    // A utility function to split the child y of this node. i is index of y in
    // child array C[]. The Child y must be full when this function is called
    void splitChild(int i, BTreeNode* y);

    // A function to traverse all nodes in a subtree rooted with this node
    void traverse();

    // A function to search a key in the subtree rooted with this node.
    BTreeNode* search(int k); // returns NULL if k is not present.

    // Make BTree friend of this so that we can access private members of this
    // class in BTree functions
    friend class BTree;
};

// A BTree
class BTree
{
    BTreeNode* root; // Pointer to root node
    int t; // Minimum degree
public:
    // Constructor (Initializes tree as empty)
    BTree(int _t)
    {
        root = NULL; t = _t;
    }

    // function to traverse the tree
    void traverse()
    {
        if (root != NULL) root->traverse();
    }

    // function to search a key in this tree
    BTreeNode* search(int k)
    {
        return (root == NULL) ? NULL : root->search(k);
    }

    // The main function that inserts a new key in this B-Tree
    void insert(int k);
};

// Constructor for BTreeNode class
BTreeNode::BTreeNode(int t1, bool leaf1)
{
    // Copy the given minimum degree and leaf property
    t = t1;
    leaf = leaf1;

    // Allocate memory for maximum number of possible keys
    // and child pointers
    keys = new int[2 * t - 1];
    C = new BTreeNode * [2 * t];

    // Initialize the number of keys as 0
    n = 0;
}

// Function to traverse all nodes in a subtree rooted with this node
void BTreeNode::traverse()
{
    // There are n keys and n+1 children, traverse through n keys
    // and first n children
    int i;
    for (i = 0; i < n; i++)
    {
        // If this is not leaf, then before printing key[i],
        // traverse the subtree rooted with child C[i].
        if (leaf == false)
            C[i]->traverse();
        cout << " " << keys[i];
    }

    // Print the subtree rooted with last child
    if (leaf == false)
        C[i]->traverse();
}

// Function to search key k in subtree rooted with this node
BTreeNode* BTreeNode::search(int k)
{
    // Find the first key greater than or equal to k
    int i = 0;
    while (i < n && k > keys[i])
        i++;

    // If the found key is equal to k, return this node
    if (keys[i] == k)
        return this;

    // If key is not found here and this is a leaf node
    if (leaf == true)
        return NULL;

    // Go to the appropriate child
    return C[i]->search(k);
}

// The main function that inserts a new key in this B-Tree
void BTree::insert(int k)
{
    // If tree is empty
    if (root == NULL)
    {
        // Allocate memory for root
        root = new BTreeNode(t, true);
        root->keys[0] = k; // Insert key
        root->n = 1; // Update number of keys in root
    }
    else // If tree is not empty
    {
        // If root is full, then tree grows in height
        if (root->n == 2 * t - 1)
        {
            // Allocate memory for new root
            BTreeNode* s = new BTreeNode(t, false);

            // Make old root as child of new root
            s->C[0] = root;

            // Split the old root and move 1 key to the new root
            s->splitChild(0, root);

            // New root has two children now. Decide which of the
            // two children is going to have new key
            int i = 0;
            if (s->keys[0] < k)
                i++;
            s->C[i]->insertNonFull(k);

            // Change root
            root = s;
        }
        else // If root is not full, call insertNonFull for root
            root->insertNonFull(k);
    }
}

// A utility function to insert a new key in this node
// The assumption is, the node must be non-full when this
// function is called
void BTreeNode::insertNonFull(int k)
{
    // Initialize index as index of rightmost element
    int i = n - 1;

    // If this is a leaf node
    if (leaf == true)
    {
        // The following loop does two things
        // a) Finds the location of new key to be inserted
        // b) Moves all greater keys to one place ahead
        while (i >= 0 && keys[i] > k)
        {
            keys[i + 1] = keys[i];
            i--;
        }

        // Insert the new key at found location
        keys[i + 1] = k;
        n = n + 1;
    }
    else // If this node is not leaf
    {
        // Find the child which is going to have the new key
        while (i >= 0 && keys[i] > k)
            i--;

        // See if the found child is full
        if (C[i + 1]->n == 2 * t - 1)
        {
            // If the child is full, then split it
            splitChild(i + 1, C[i + 1]);

            // After split, the middle key of C[i] goes up and
            // C[i] is splitted into two. See which of the two
            // is going to have the new key
            if (keys[i + 1] < k)
                i++;
        }
        C[i + 1]->insertNonFull(k);
    }
}

// A utility function to split the child y of this node
// Note that y must be full when this function is called
void BTreeNode::splitChild(int i, BTreeNode* y)
{
    // Create a new node which is going to store (t-1) keys
    // of y
    BTreeNode* z = new BTreeNode(y->t, y->leaf);
    z->n = t - 1;

    // Copy the last (t-1) keys of y to z
    for (int j = 0; j < t - 1; j++)
        z->keys[j] = y->keys[j + t];

    // Copy the last t children of y to z
    if (y->leaf == false)
    {
        for (int j = 0; j < t; j++)
            z->C[j] = y->C[j + t];
    }

    // Reduce the number of keys in y
    y->n = t - 1;

    // Since this node is going to have a new child,
    // create space of new child
    for (int j = n; j >= i + 1; j--)
        C[j + 1] = C[j];

    // Link the new child to this node
    C[i + 1] = z;

    // A key of y will move to this node. Find the location of
    // new key and move all greater keys one space ahead
    for (int j = n - 1; j >= i; j--)
        keys[j + 1] = keys[j];

    // Copy the middle key of y to this node
    keys[i] = y->keys[t - 1];

    // Increment count of keys in this node
    n = n + 1;
}

// Driver program to test above functions
int main()
{
    BTree t(3); // A B-Tree with minimum degree 3
    t.insert(10);
    t.insert(20);
    t.insert(5);
    t.insert(6);
    t.insert(12);
    t.insert(30);
    t.insert(7);
    t.insert(17);

    cout << "Traversal of the constructed tree is ";
    t.traverse();

    int k = 6;
    (t.search(k) != NULL) ? cout << "\nPresent" : cout << "\nNot Present";

    k = 15;
    (t.search(k) != NULL) ? cout << "\nPresent" : cout << "\nNot Present";

    return 0;
}
 

2 代码格式

#include<iostream>
using namespace std;// A BTree node
class BTreeNode
{int* keys; // An array of keysint t;	 // Minimum degree (defines the range for number of keys)BTreeNode** C; // An array of child pointersint n;	 // Current number of keysbool leaf; // Is true when node is leaf. Otherwise false
public:BTreeNode(int _t, bool _leaf); // Constructor// A utility function to insert a new key in the subtree rooted with// this node. The assumption is, the node must be non-full when this// function is calledvoid insertNonFull(int k);// A utility function to split the child y of this node. i is index of y in// child array C[]. The Child y must be full when this function is calledvoid splitChild(int i, BTreeNode* y);// A function to traverse all nodes in a subtree rooted with this nodevoid traverse();// A function to search a key in the subtree rooted with this node.BTreeNode* search(int k); // returns NULL if k is not present.// Make BTree friend of this so that we can access private members of this// class in BTree functionsfriend class BTree;
};// A BTree
class BTree
{BTreeNode* root; // Pointer to root nodeint t; // Minimum degree
public:// Constructor (Initializes tree as empty)BTree(int _t){root = NULL; t = _t;}// function to traverse the treevoid traverse(){if (root != NULL) root->traverse();}// function to search a key in this treeBTreeNode* search(int k){return (root == NULL) ? NULL : root->search(k);}// The main function that inserts a new key in this B-Treevoid insert(int k);
};// Constructor for BTreeNode class
BTreeNode::BTreeNode(int t1, bool leaf1)
{// Copy the given minimum degree and leaf propertyt = t1;leaf = leaf1;// Allocate memory for maximum number of possible keys// and child pointerskeys = new int[2 * t - 1];C = new BTreeNode * [2 * t];// Initialize the number of keys as 0n = 0;
}// Function to traverse all nodes in a subtree rooted with this node
void BTreeNode::traverse()
{// There are n keys and n+1 children, traverse through n keys// and first n childrenint i;for (i = 0; i < n; i++){// If this is not leaf, then before printing key[i],// traverse the subtree rooted with child C[i].if (leaf == false)C[i]->traverse();cout << " " << keys[i];}// Print the subtree rooted with last childif (leaf == false)C[i]->traverse();
}// Function to search key k in subtree rooted with this node
BTreeNode* BTreeNode::search(int k)
{// Find the first key greater than or equal to kint i = 0;while (i < n && k > keys[i])i++;// If the found key is equal to k, return this nodeif (keys[i] == k)return this;// If key is not found here and this is a leaf nodeif (leaf == true)return NULL;// Go to the appropriate childreturn C[i]->search(k);
}// The main function that inserts a new key in this B-Tree
void BTree::insert(int k)
{// If tree is emptyif (root == NULL){// Allocate memory for rootroot = new BTreeNode(t, true);root->keys[0] = k; // Insert keyroot->n = 1; // Update number of keys in root}else // If tree is not empty{// If root is full, then tree grows in heightif (root->n == 2 * t - 1){// Allocate memory for new rootBTreeNode* s = new BTreeNode(t, false);// Make old root as child of new roots->C[0] = root;// Split the old root and move 1 key to the new roots->splitChild(0, root);// New root has two children now. Decide which of the// two children is going to have new keyint i = 0;if (s->keys[0] < k)i++;s->C[i]->insertNonFull(k);// Change rootroot = s;}else // If root is not full, call insertNonFull for rootroot->insertNonFull(k);}
}// A utility function to insert a new key in this node
// The assumption is, the node must be non-full when this
// function is called
void BTreeNode::insertNonFull(int k)
{// Initialize index as index of rightmost elementint i = n - 1;// If this is a leaf nodeif (leaf == true){// The following loop does two things// a) Finds the location of new key to be inserted// b) Moves all greater keys to one place aheadwhile (i >= 0 && keys[i] > k){keys[i + 1] = keys[i];i--;}// Insert the new key at found locationkeys[i + 1] = k;n = n + 1;}else // If this node is not leaf{// Find the child which is going to have the new keywhile (i >= 0 && keys[i] > k)i--;// See if the found child is fullif (C[i + 1]->n == 2 * t - 1){// If the child is full, then split itsplitChild(i + 1, C[i + 1]);// After split, the middle key of C[i] goes up and// C[i] is splitted into two. See which of the two// is going to have the new keyif (keys[i + 1] < k)i++;}C[i + 1]->insertNonFull(k);}
}// A utility function to split the child y of this node
// Note that y must be full when this function is called
void BTreeNode::splitChild(int i, BTreeNode* y)
{// Create a new node which is going to store (t-1) keys// of yBTreeNode* z = new BTreeNode(y->t, y->leaf);z->n = t - 1;// Copy the last (t-1) keys of y to zfor (int j = 0; j < t - 1; j++)z->keys[j] = y->keys[j + t];// Copy the last t children of y to zif (y->leaf == false){for (int j = 0; j < t; j++)z->C[j] = y->C[j + t];}// Reduce the number of keys in yy->n = t - 1;// Since this node is going to have a new child,// create space of new childfor (int j = n; j >= i + 1; j--)C[j + 1] = C[j];// Link the new child to this nodeC[i + 1] = z;// A key of y will move to this node. Find the location of// new key and move all greater keys one space aheadfor (int j = n - 1; j >= i; j--)keys[j + 1] = keys[j];// Copy the middle key of y to this nodekeys[i] = y->keys[t - 1];// Increment count of keys in this noden = n + 1;
}// Driver program to test above functions
int main()
{BTree t(3); // A B-Tree with minimum degree 3t.insert(10);t.insert(20);t.insert(5);t.insert(6);t.insert(12);t.insert(30);t.insert(7);t.insert(17);cout << "Traversal of the constructed tree is ";t.traverse();int k = 6;(t.search(k) != NULL) ? cout << "\nPresent" : cout << "\nNot Present";k = 15;(t.search(k) != NULL) ? cout << "\nPresent" : cout << "\nNot Present";return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/207159.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

dell服务器重启后显示器黑屏

1.硬件层面&#xff1a;观察主机的指示灯 &#xff08;1&#xff09;指示灯偏黄&#xff0c;硬件存在问题&#xff08;内存条有静电&#xff0c;拔出后用橡皮擦擦拭&#xff1b;或GPU松动&#xff09; a.电源指示灯黄&#xff0c;闪烁三下再闪烁一下&#xff0c;扣下主板上的纽…

Python Appium Selenium 查杀进程的实用方法

一、前置说明 在自动化过程中&#xff0c;经常需要在命令行中执行一些操作&#xff0c;比如启动应用、查杀应用等&#xff0c;因此可以封装成一个CommandExecutor来专门处理这些事情。 二、操作步骤 # cmd_util.pyimport logging import os import platform import shutil i…

Java编程中通用的正则表达式(二)

正则表达式&#xff0c;又称正则式、规则表达式、正规表达式、正则模式或简称正则&#xff0c;是一种用来匹配字符串的工具。它是一种字符串模式的表示方法&#xff0c;可以用来检索、替换和验证文本。正则表达式是一个字符串&#xff0c;它描述了一些字符的组合&#xff0c;这…

dockers安装rabbitmq

RabbitMQ: easy to use, flexible messaging and streaming — RabbitMQhttps://www.rabbitmq.com/ Downloading and Installing RabbitMQ — RabbitMQ docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.12-management 之后参照&#xff1a;dock…

高低压配电智能监控系统

高低压配电智能监控系统是一种综合运用物联网、云计算、大数据和人工智能等技术的智能化监控系统&#xff0c;主要用于对高低压配电设备进行实时监测、数据采集、故障预警和远程管理。 该系统通过安装智能传感器、智能设备、网络通讯技术等手段&#xff0c;依托电易云-智慧电力…

解决“由于找不到msvcr110.dll无法继续执行”的错误问题,一键修复msvcr110.dll丢失

当你遇到“由于找不到msvcr110.dll无法继续执行”的错误时&#xff0c;通常是因为你的电脑缺少相关的msvcr110.dll文件。如果你的电脑中缺失了msvcr110.dll文件丢失那么可以根据下面的方法尝试解决msvcr110.dll丢失的问题。 一.解决msvcr110.dll丢失的方法 使用dll修复工具 D…

学习笔记9——JUC三种量级的锁机制

学习笔记系列开头惯例发布一些寻亲消息 链接&#xff1a;https://baobeihuijia.com/bbhj/contents/3/197325.html 多线程访问共享资源冲突 临界区&#xff1a;一段代码块存在对共享资源的多线程读写操作&#xff0c;称这段代码块为临界区 竞态条件&#xff1a;多个线程在临界…

yolo目标检测+目标跟踪+车辆计数+车辆分割+车道线变更检测+速度估计

这个项目使用YOLO进行车辆检测&#xff0c;使用SORT&#xff08;简单在线实时跟踪器&#xff09;进行车辆跟踪。该项目实现了以下任务&#xff1a; 车辆计数车道分割车道变更检测速度估计将所有这些详细信息转储到CSV文件中 车辆计数是指在道路上安装相应设备&#xff0c;通过…

windows下 Tomcat启动黑框隐藏

进入到 tomcat/bin 目录下&#xff0c;找到此文件 setclasspath.bat &#xff0c;右键文本打开 找到此属性 &#xff1a; set _RUNJAVA"%JRE_HOME%\bin\java.exe"修改成以下属性&#xff0c;保存文件&#xff0c;重启启动tomcat会发现黑框不默认弹出了&#xff1a; …

使用hutool工具生成非对称加密公私密钥以及使用案例

1.导入hutool依赖 <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.18</version></dependency>2.直接复制代码 package com.common.utils;import cn.hutool.core.codec.Base64; i…

仅需30秒完美复刻任何人的声音 - 最强AI音频11Labs

我的用词一直都挺克制的&#xff0c;基本不会用到“最强”这个字眼。 但是这一次的这个AI应用&#xff0c;是我认为在TTS&#xff08;文字转音频&#xff09;这个领域&#xff0c;当之无愧的“最强”。 ElevenLabs&#xff0c;简称11Labs。 仅需30秒到5分钟左右的极少的数据集…

机器学习-分类问题

前言 《机器学习-回归问题》知道了回归问题的处理方式,分类问题才是机器学习的重点.从数据角度讲,回归问题可以转换为分类问题的微分 逻辑回归 逻辑回归&#xff08;Logistics Regression&#xff09;,逻辑回归虽然带有回归字样&#xff0c;但是逻辑回归属于分类算法。但只可…

极大提升GPT-4等模型推理效率,微软、清华开源全新框架

随着用户需求的增多&#xff0c;GPT-4、Claude等模型在文本生成、理解、总结等方面的能力越来越优秀。但推理的效率并不高&#xff0c;因为&#xff0c;多数主流模型采用的是“顺序生成词”方法&#xff0c;会导致GPU利用率很低并带来高延迟。 为了解决这一难题&#xff0c;清…

基于jsp+servlet的图书管理系统

基于jspservlet的图书管理系统演示地址为 图书馆后台管理系统 用户名:mr ,密码:123 图书馆管理系统主要的目的是实现图书馆的信息化管理。图书馆的主要业务就是新书的借阅和归还&#xff0c; 因此系统最核心的功能便是实现图书的借阅和归还。此外&#xff0c;还需要提供图书…

Stable Diffusion XL on diffusers

Stable Diffusion XL on diffusers 翻译自&#xff1a;https://huggingface.co/docs/diffusers/using-diffusers/sdxl v0.24.0 非逐字翻译 Stable Diffusion XL (SDXL) 是一个强大的图像生成模型&#xff0c;其在上一代 Stable Diffusion 的基础上主要做了如下优化&#xff1a;…

生产上线需要注意的安全漏洞

一、关闭swagger 1、关闭swagger v3 # 需同时设置auto-startupfalse&#xff0c;否则/v3/api-docs等接口仍能继续访问 springfox:documentation:enabled: falseauto-startup: falseswagger-ui:enabled: false 2、关闭swagger v2 # 只要不是true就不启用 swagger:enable: fa…

代立冬:基于Apache Doris+SeaTunnel 实现多源实时数据仓库解决方案探索实践

大家好&#xff0c;我是白鲸开源的联合创始人代立冬&#xff0c;同时担任 Apache DolphinScheduler 的 PMC chair 和 SeaTunnel 的 PMC。作为 Apache Foundation 的成员和孵化器导师&#xff0c;我积极参与推动多个开源项目的发展&#xff0c;帮助它们通过孵化器成长为 Apache …

某度旋转验证码v2 逆向分析

v2主要依据是核心 JS 文件mkd_v2.js 版本&#xff0c;如下图所示&#xff1a; 第一次 https://passport.baidu.com/cap/init 接口&#xff0c;请求的 ak 是固定值&#xff0c;当然不同场景不同网站是不一样的&#xff0c;_ 时间戳&#xff0c;ver1&#xff0c;返回值 as、tk 都…

android项目实战之使用框架 集成多图片、视频的上传

效果图 实现方式&#xff0c;本功能使用PictureSelector 第三方库 。作者项目地址&#xff1a;https://github.com/LuckSiege/PictureSelector 1. builder.gradle 增加 implementation io.github.lucksiege:pictureselector:v3.11.1implementation com.tbruyelle.rxpermissio…

线性回归实战

3.1 使用正规方程进行求解 3.1.1 简单线性回归 公式 &#xff1a; y w x b y wx b ywxb 一元一次方程&#xff0c;在机器学习中一元表示一个特征&#xff0c;b表示截距&#xff0c;y表示目标值。 使用代码进行实现&#xff1a; 导入包 import numpy as np import matp…