-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree.c
More file actions
125 lines (110 loc) · 2.58 KB
/
Copy pathbinary_tree.c
File metadata and controls
125 lines (110 loc) · 2.58 KB
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
115
116
117
118
119
120
121
122
123
124
125
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "tokenize.h"
#define BUF_SIZE 1024
char buffer[BUF_SIZE];
struct node {
int data;
struct node* left;
struct node* right;
};
static struct node* entry;
struct node* found;
struct node* leftest;
struct node tmp;
struct node* lookup(struct node* node, int value) {
if (node == NULL)
return false;
else {
if (value == node->data)
return node;
else if (value < node->data)
return lookup(node->left, value);
return lookup(node->right, value);
}
}
struct node* NewNode(int data) {
struct node* node = malloc(sizeof(*node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
struct node* insert(struct node* node, int data) {
if (node == NULL)
return NewNode(data);
else {
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
return node;
}
}
int delete(struct node* node, int value) {
found = lookup(node, value);
if (found->right != NULL){
leftest = found->right;
while (leftest->left)
leftest = leftest->left;
found->data = leftest->data;
if (leftest->right)
insert(found, leftest->right->data);
free(leftest);
leftest = NULL;
}
else if (found->left != NULL){
found->data = found->left->data;
found->right = found->left->right;
tmp = *(found->left->left);
found->left = &tmp;
free(found->left);
found->left = NULL;
}
else {
free(found);
if (memcmp(found, entry, sizeof(found)) == 0)
entry = NULL;
}
return 0;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~ Utils ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
char *command;
int *idata;
int dvalue;
char **tokens;
char *tok;
void main(){
while (fgets(buffer, BUF_SIZE, stdin)) {
tokens = tokenize(buffer);
command = tokens[0];
dvalue = atoi(tokens[1]);
idata = &dvalue;
if (strcmp(command, "insert") == 0) {
if (entry != NULL)
insert(entry, *idata);
else
printf("Inserting %d\n", *idata);
entry = NewNode(*idata);
}
else if (strcmp(command, "lookup") == 0) {
if (entry && (found = lookup(entry, *idata)))
printf("Found: %d\n", found->data);
else if (!entry)
printf("The tree is empty\n");
else if (!found)
printf("%d not in the tree\n", *idata);
}
else if (strcmp(command, "delete") == 0)
if (entry != NULL)
delete(entry, *idata);
else
exit(0);
else {
printf("Invalid command: %s\n", command);
exit(0);
}
}
}