Skip to content

Instantly share code, notes, and snippets.

@sat0b
Last active October 28, 2017 05:29
Show Gist options
  • Select an option

  • Save sat0b/ccb09b9a8b3d097a1bdbd71f78605703 to your computer and use it in GitHub Desktop.

Select an option

Save sat0b/ccb09b9a8b3d097a1bdbd71f78605703 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct _tree {
int value;
struct _tree *left;
struct _tree *right;
} Tree;
Tree *tree_init(int value) {
Tree *tree = malloc(sizeof(Tree));
tree->value = value;
tree->left = NULL;
tree->right = NULL;
return tree;
}
int tree_insert(Tree **p, int value) {
while (*p) {
if (value == (*p)->value)
return 0;
else if (value < (*p)->value)
p = &(*p)->left;
else
p = &(*p)->right;
}
*p = tree_init(value);
return 1;
}
Tree *tree_find(Tree *p, int value) {
while (p) {
if (value == p->value)
return p;
else if (value < p->value)
p = p->left;
else
p = p->right;
}
return NULL;
}
int tree_delete(Tree **p, int value) {
while (*p) {
if (value == (*p)->value) {
Tree *tmp = *p;
if ((*p)->left == NULL && (*p)->right == NULL) {
*p = NULL;
} else if ((*p)->right == NULL) {
*p = (*p)->left;
} else if ((*p)->left == NULL) {
*p = (*p)->right;
} else {
Tree **x = p;
while ((*x)->right)
x = &(*x)->right;
Tree *xp = *x;
*x = (*x)->left;
xp->left = (*p)->left;
xp->right = (*p)->right;
*p = xp;
}
free(tmp);
return 1;
} else if (value < (*p)->value) {
p = &(*p)->left;
} else {
p = &(*p)->right;
}
}
return 0;
}
int main() {
Tree *t = tree_init(5);
tree_insert(&t, 3);
tree_insert(&t, 6);
tree_insert(&t, 8);
printf("%d\n", t->value);
printf("%d\n", t->left->value);
printf("%d\n", t->right->value);
tree_delete(&t, 3);
printf("%p\n", t->left);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment