Last active
June 21, 2024 22:00
-
-
Save rugyoga/208b809fb8b700263b2508241a2d7a04 to your computer and use it in GitHub Desktop.
C implementation of a binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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