Skip to content

Instantly share code, notes, and snippets.

@johnciacia
Created November 22, 2012 05:16
Show Gist options
  • Select an option

  • Save johnciacia/4129512 to your computer and use it in GitHub Desktop.

Select an option

Save johnciacia/4129512 to your computer and use it in GitHub Desktop.
Implementation of a Binary Tree
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct node {
struct node *left;
struct node *right;
int val;
} node;
void insert(node **tree, node *item) {
if(NULL == *tree) {
*tree = item;
return;
}
if(item->val < (*tree)->val) {
insert(&(*tree)->left, item);
} else {
insert(&(*tree)->right, item);
}
}
void print(node *tree) {
if(tree->left) {
print(tree->left);
}
printf("%d\n", tree->val);
if(tree->right) {
print(tree->right);
}
}
int main(void) {
node *current, *tree;
int i;
tree = NULL;
srand(time(NULL));
for(i = 0; i < 10; i++) {
current = (node *)malloc(sizeof(node));
current->left = NULL;
current->right = NULL;
current->val = rand();
insert(&tree, current);
}
print(tree);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment