Skip to content

Instantly share code, notes, and snippets.

@rugyoga
Last active June 21, 2024 22:00
Show Gist options
  • Save rugyoga/208b809fb8b700263b2508241a2d7a04 to your computer and use it in GitHub Desktop.
Save rugyoga/208b809fb8b700263b2508241a2d7a04 to your computer and use it in GitHub Desktop.
C implementation of a binary tree
#include <stdio.h>
#include <stdlib.h>
struct tree
{
struct tree *left;
int value;
struct tree *right;
};
typedef struct tree * treep;
treep new(int value) {
treep t = malloc(sizeof(struct tree));
t->value = value;
t->left = NULL;
t->right = NULL;
return t;
}
void insert(treep* tp, int value) {
treep t = *tp;
if (t == NULL)
*tp = new(value);
else if (value < t->value)
insert(&(t->left), value);
else if (value > t->value)
insert(&(t->right), value);
}
void traverse(treep t){
if (t != NULL) {
traverse(t->left);
printf("%d\n", t->value);
traverse(t->right);
}
}
int main()
{
treep t = NULL;
insert(&t, 4);
insert(&t, 2);
insert(&t, 6);
insert(&t, 1);
insert(&t, 3);
insert(&t, 5);
insert(&t, 7);
traverse(t);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment