C implementation of Binary Search Tree

preview_player
Показать описание
Music credits-
Music : Another time
Musician : LiQWYD

For more related content, visit channel.
Рекомендации по теме
Комментарии
Автор

// Here is the code
#include<stdio.h>
#include<stdlib.h>

struct tree{
int key;
struct tree *left, *right;
};

struct tree* create(int data){
struct tree* newnode = (struct tree*)malloc(sizeof(struct tree));
if(newnode == NULL){
return NULL;
}
newnode->key = data;
newnode->left = newnode->right = NULL;
return newnode;
}
struct tree* insert(struct tree* root, int data){
if(root == NULL){
root = create(data);
return root;
}
if(data < root->key){
root->left = insert(root->left, data);
}
if(data > root->key){
root->right = insert(root->right, data);
}
return root;
}

struct tree* delete(struct tree* root, int data){
if(root== NULL) return root;
if(data < root->key){
root->left = delete(root->left, data);
}
else if(data > root->key){
root->right = delete(root->right, data);
}
else{
if(root->left == NULL){
struct tree* temp = root->right;
free(root);
return temp;
}
else if(root->right == NULL){
struct tree* temp = root->left;
free(root);
return temp;
}
struct tree* temp = root->right;
while(temp->left!=NULL){
temp=temp->left;
}
root->key = temp->key;
root->right = delete(root->right, temp->key);
}
return root;
}

void inorder(struct tree* root){
if(root!=NULL){
inorder(root->left);
printf("%d-> ", root->key);
inorder(root->right);
}
}


int main(){
struct tree* root = NULL;
root = insert(root, 20);
insert(root, 45);
insert(root, 15);
insert(root, 5);
insert(root, 25);
insert(root, 40);
insert(root, 11);
insert(root, 2);
insert(root, 33);
insert(root, 6);
inorder(root);
printf("\n");
delete(root, 33);
inorder(root);
printf("\n");
delete(root, 5);
inorder(root);
printf("\n");
delete(root, 25);
inorder(root);
printf("\n");
return 0;
}

snehaiitian