今天我们将学习 bst 以及如何将单个元素(或者我们可以说单个节点)插入 bst**。对于那些已经了解 bst 和双链表的人来说,这很容易,在阅读本文之前,这些主题很重要。所以我提供了这些主题的链接,您可以参考它。-
1.对于双链表
2.对于二叉树
所以在了解如何将单个节点插入 bst 之前。你一定要知道bst是什么,bst是一个
** 二叉搜索树** 它具有一些属性,例如 :-
- 左节点的值较小或与根和右元素相比
- 根节点与右节点相比具有较小的值
- 当我们通过应用中序三叉树对节点进行三叉树时,它将 给出升序排序数组。
看起来像这样
为了将元素插入 bst,我们需要一个指向根节点的指针,因为在某些部分我们必须将密钥与根数据进行比较,以便我们知道密钥将插入到左侧还是右侧。
首先我们创建一个节点并将其初始化为 bst。
这是您可以参考的代码,代码是用 c 语言实现的。
#include<stdio.h>
#include<stdlib.h>
struct 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("%d
",head1->right->right->data);
inOrder(head1);
return 0;
}
以上就是如何将元素插入 BST (DSA) ?的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论