forked from a-r-nida/HactoberFest2020-Beginers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarytree.c
114 lines (101 loc) · 2.39 KB
/
binarytree.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include<stdio.h>
#include<stdlib.h>
struct btree{
int data;
struct btree *left;
struct btree *right;
};
struct btree *minValueNode(struct btree* node){
struct btree* current = node;
/* loop down to find the leftmost leaf */
while (current && current->left != NULL)
current = current->left;
return current;
}
void insert(struct btree **root, int newData){
struct btree *node = (*root);
if(node == NULL){
struct btree *newNode = (struct btree *)malloc(sizeof(struct btree));
newNode->left = NULL;
newNode->data = newData;
newNode->right = NULL;
*root = newNode;
}
else{
if(newData > node->data)
insert(&(node->right), newData);
else
insert(&(node->left), newData);
}
}
struct btree *delete(struct btree *root, int item){
if(root == NULL)
return root;
if(item > root->data)
root->right = delete(root->right, item);
else if(item < root->data)
root->left = delete(root->left, item);
else{
if(root->left == NULL){
struct btree *temp = root->right;
free(root);
return temp;
}
if(root->right == NULL){
struct btree *temp = root->left;
free(root);
return temp;
}
struct btree *temp = minValueNode(root->right);
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
return root;
}
void inorder(struct btree *root){
if(root != NULL){
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
else{
return;
}
}
void preorder(struct btree *root){
if(root != NULL){
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
else{
return;
}
}
void postorder(struct btree *root){
if(root != NULL){
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
else{
return;
}
}
int main(){
struct btree *root = NULL;
insert(&root, 20);
insert(&root, 40);
insert(&root, 17);
insert(&root, 6);
insert(&root, 8);
insert(&root, 10);
insert(&root, 7);
inorder(root);
printf("\n");
delete(root, 20);
inorder(root);
printf("\n");
postorder(root);
return 0;
}