Created
November 22, 2012 05:16
-
-
Save johnciacia/4129512 to your computer and use it in GitHub Desktop.
Implementation of a Binary Tree
This file contains hidden or 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> | |
| #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