0% found this document useful (0 votes)
3 views

Binary search tree

Uploaded by

premsrnvs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Binary search tree

Uploaded by

premsrnvs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>

struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* createNode(int value) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

struct Node* insert(struct Node* root, int value) {


if (root == NULL)
return createNode(value);
if (value < root->data)
root->left = insert(root->left, value);
if (value > root->data)
root->right = insert(root->right, value);
return root;
}

struct Node* minValueNode(struct Node* node) {


while (node->left != NULL)
node = node->left;
return node;
}

struct Node* deleteNode(struct Node* root, int key) {


if (root == NULL)
return root;
if (key < root->data)
root->left = deleteNode(root->left, key);
if (key > root->data)
root->right = deleteNode(root->right, key);
else {
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
}
if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
struct Node* temp = minValueNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}

void inOrder(struct Node* root) {


if (root != NULL) {
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}

int main() {
struct Node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 70);
insert(root, 20);
insert(root, 40);
insert(root, 60);
insert(root, 80);

inOrder(root);
printf("\n");
root = deleteNode(root, 50);
inOrder(root);
return 0;
}

You might also like