如何将元素插入 BST (DSA) ?

今天我们将学习 bst 以及如何将单个元素(或者我们可以说单个节点)插入 bst**。对于那些已经了解 bst 和双链表的人来说,这很容易,在阅读本文之前,这些主题很重要。所以我提供了这些主题的链接,您可以参考它。-

1.对于双链表
2.对于二叉树

所以在了解如何将单个节点插入 bst 之前。你一定要知道bst是什么,bst是一个

** 二叉搜索树** 它具有一些属性,例如 :-

左节点的值较小或与根和右元素相比根节点与右节点相比具有较小的值当我们通过应用中序三叉树对节点进行三叉树时,它将 给出升序排序数组。

看起来像这样
如何将元素插入 BST (DSA) ?

为了将元素插入 bst,我们需要一个指向根节点的指针,因为在某些部分我们必须将密钥与根数据进行比较,以便我们知道密钥将插入到左侧还是右侧。

image description

首先我们创建一个节点并将其初始化为 bst。

这是您可以参考的代码,代码是用 c 语言实现的。

#include#includestruct node{   struct node* left;   int data;   struct node* right;};struct node* createNode(int key){   struct node * newNode = NULL;   newNode = malloc(sizeof(struct node));   newNode->left = NULL;   newNode->data = key;   newNode->right = NULL;   return newNode;}void insertNewNode(struct node* root , int key){    struct node * prev = NULL;    while(root!=NULL){        prev = root;        if(key==root){            printf("element cannot insert it is present                               inside the bst already");            return ;        }        else if(key>root->data)        {                   root = root->right;        }        else{            root = root->left;        }    }    struct node * newNode = createNode(key);    if(key>prev->data){        prev->right = newNode;    }    else{        prev->left = newNode;    }}void inOrder(struct node* root){     if(root == NULL){        return root;    }    inOrder(root->left);    printf("%d",root->data1`1);    inOrder(root->right);}int main(){    struct node* head1 = createBst(20);    struct node* head2 = createBst(10);    struct node* head3 = createBst(30);    head1->left=head2;    head1->right=head3;    insertNewNode(head1,40);    printf("%dn",head1->right->right->data);    inOrder(head1);    return 0;}

以上就是如何将元素插入 BST (DSA) ?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1461089.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
C Programming: A Short and Simple Guide To break, continue, and switch
上一篇 2025年12月18日 13:02:56
制表符与空格 — C 中的 Makefile
下一篇 2025年12月18日 13:03:04

相关推荐

发表回复

登录后才能评论
关注微信