Skip to content
Snippets Groups Projects
Commit 90e54c6b authored by Boris Stefanovic's avatar Boris Stefanovic
Browse files

save

parent d209a624
Branches
No related tags found
No related merge requests found
...@@ -2,5 +2,110 @@ ...@@ -2,5 +2,110 @@
#include <stdlib.h> #include <stdlib.h>
typedef struct node {
int value;
struct node *l;
struct node *r;
} node_t;
struct node* node_create(const int value) {
struct node *n = malloc(sizeof(node_t));
n->value = value;
n->l = NULL;
n->r = NULL;
return n;
}
void node_insert(struct node* n, const int value) {
if (value < n->value) {
if (n->l == NULL) {
n->l = node_create(value);
} else {
node_insert(n->l, value);
}
} else if (value > n->value) {
if (n->r == NULL) {
n->r = node_create(value);
} else {
node_insert(n->r, value);
}
}
}
void tree_insert(struct node** t, const int value) {
if (NULL == (*t)) {
*t = node_create(value);
} else {
node_insert(*t, value);
}
}
void tree_destroy(struct node* n) {
if (n != NULL) {
tree_destroy(n->l);
tree_destroy(n->r);
free(n);
}
}
typedef struct stackitem {
char value;
struct stackitem* next;
} stackitem_t;
void stack_push(stackitem_t** s, char value) {
stackitem_t* top = malloc(sizeof(stackitem_t));
top->value = value;
top->next = *s;
*s = top;
}
char stack_pop(stackitem_t** s) {
if (*s == NULL) return '\0';
stackitem_t *top = *s;
char c = top->value;
*s = (*s)->next;
free(top);
return c;
}
void stack_consume(stackitem_t* item) {
if (item == NULL) return;
printf("%c", item->value);
if (item->next != NULL) stack_consume(item->next);
free(item);
}
void search_path(const node_t* root, const int value, stackitem_t** s) {
if (root == NULL) return;
if (value < root->value) {
stack_push(s, 'g');
search_path(root->l, value, s);
} else if (value > root->value) {
stack_push(s, 'd');
search_path(root->r, value, s);
}
}
int main() { int main() {
const int a[] = { 10, 0, 20, -5, 5, 15, 25, 22, 24 };
const int len = 9;
struct node *root = NULL;
for (int i = 0; i < len; ++i) { tree_insert(&root, a[i]); }
stackitem_t *top = NULL;
search_path(root, 7, &top);
stack_consume(top);
printf("\n");
tree_destroy(root);
return EXIT_SUCCESS;
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment