Task 5, closes #5

This commit is contained in:
Inex Code 2020-05-21 05:59:52 +03:00
parent 9a9e9b28f7
commit 0233e876c4

152
task5/task5.c Normal file
View file

@ -0,0 +1,152 @@
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct bstree {
int key;
char *value;
struct bstree *left;
struct bstree *right;
} TREE_NODE;
TREE_NODE *tree_create(int key, char *value) {
TREE_NODE *node;
node = malloc(sizeof(TREE_NODE));
if (node == NULL) {
fprintf(stderr, "Error allocating node");
return NULL;
}
node->key = key;
node->value = value;
node->left = NULL;
node->right = NULL;
return node;
}
void add_leaf(int key, char *value, TREE_NODE *tree) {
TREE_NODE *node;
node = tree_create(key, value);
if (tree == NULL) {
return;
}
while (tree != NULL) {
if (key < tree->key) {
if (tree->left == NULL) {
tree->left = node;
return;
} else {
tree = tree->left;
}
} else if (key > tree->key) {
if (tree->right == NULL) {
tree->right = node;
return;
} else {
tree = tree->right;
}
} else
return;
}
}
TREE_NODE *tree_lookup(TREE_NODE *tree, int key) {
while (tree != NULL) {
if (key == tree->key) {
return tree;
} else if (key < tree->key) {
tree = tree->left;
} else {
tree = tree->right;
}
}
return tree;
}
TREE_NODE *parent_lookup(TREE_NODE *tree, int key) {
while (tree != NULL) {
if ((tree->left != NULL && (key == (tree->left)->key)) ||
(tree->right != NULL && (key == (tree->right)->key))) {
return tree;
} else if (key < tree->key) {
tree = tree->left;
} else {
tree = tree->right;
}
}
return tree;
}
void delete_node(TREE_NODE *tree, int key) {
TREE_NODE *node = tree_lookup(tree, key);
tree = parent_lookup(tree, key);
if (node->left == NULL && node->right == NULL) {
if (tree->left == node) {
free(node);
tree->left = NULL;
} else {
free(node);
tree->right = NULL;
}
} else if (node->left != NULL && node->right == NULL) {
if (tree->left == node) {
tree->left = node->left;
free(node);
} else {
tree->right = node->left;
free(node);
}
} else if (node->left == NULL && node->right != NULL) {
if (tree->left == node) {
tree->left = node->right;
free(node);
} else {
tree->right = node->right;
free(node);
}
} else {
if ((node->right)->left == NULL) {
tree = node->right;
node->key = tree->key;
node->value = tree->value;
node->right = tree->right;
free(tree);
} else {
tree = node;
while (tree->left != NULL) {
tree = tree->left;
}
node->key = tree->key;
node->value = tree->value;
free(tree);
}
}
return;
}
int main(int argc, char const *argv[]) {
TREE_NODE *tree;
tree = tree_create(180, "First");
add_leaf(50, "second", tree);
add_leaf(250, "third", tree);
add_leaf(40, "fourth", tree);
add_leaf(30, "fifth", tree);
add_leaf(45, "sixth", tree);
add_leaf(44, "seventh", tree);
delete_node(tree, 45);
return 0;
}
/*
180
/ \
50 250
/
40
/ \
30 45
/
44
*/