-
Notifications
You must be signed in to change notification settings - Fork 1
/
binary_search_tree_delete_node.c
81 lines (74 loc) · 2.21 KB
/
binary_search_tree_delete_node.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include<stdlib.h>
#include<stdio.h>
struct TreeNode{ // node for the binary tree
int data;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* GenerateNode(int data){ // generate new node
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct TreeNode* Insert(struct TreeNode* root,int data){ // insert new node using recursion
if(root == NULL){
root = GenerateNode(data);
return root;
}
if(data <= root->data){
root->left = Insert(root->left, data); // recursion call
} else {
root->right = Insert(root->right, data); // recursion call
}
return root;
}
struct TreeNode* FindMin(struct TreeNode* root){
if(root == NULL){
printf("Error: tree is empty");
return -1;
}
else if(root->left == NULL) return root;
return FindMin(root->left);
}
struct TreeNode* Delete(struct TreeNode* root, int data){
if(root == NULL) return root;
else if(data < root->data) root->left = Delete(root->left, data);
else if(data > root->data) root->right = Delete(root->right, data);
else{ // node is the one that needs to be deleted
// Case 1: node has no children
if(root->left == NULL && root->right == NULL){
free(root);
root = NULL;
}
// Case 2: node has a single child
else if(root->left == NULL){
struct TreeNode* temp = root;
root = root->right;
free(temp);
}
else if(root->right == NULL){
struct TreeNode* temp = root;
root = root->left;
free(temp);
}
// Case 3: node has 2 children
else{
struct TreeNode* temp = FindMin(root->right);
root->data = temp->data;
root->right = Delete(root->right, temp->data);
}
}
return root;
}
// TEST>>>>NOT PART OF IMPLEMENTATION
int main(){
struct TreeNode* root = NULL;
root = Insert(root, 20);
root = Insert(root, 15);
root = Insert(root, 2);
root = Insert(root, 5);
root = Insert(root, 3);
Delete(root, 3);
}