How to build, print and free a binary tree of int numbers in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h> 
 
struct node 
{ 
    int val;
    struct node *left; 
    struct node *right; 
}; 
 
#define VAL_COUNT 3
 
struct node *add_to_tree(struct node *n, int num);
void print_tree(struct node *n);
void free_tree(struct node *n);
 
int main(void)
{
    struct node *root = NULL;
    int i = 0;
	
	srand((unsigned)time(NULL));
     
    while (i < VAL_COUNT)
    {
           root = add_to_tree(root, rand() % 100 + 1);
           i++;
    }
	
    print_tree(root);
    
    return 0;
}
struct node *add_to_tree(struct node *n, int num)
{
    if (n == NULL) 
    { 
        if ( (n = (struct node *) malloc(sizeof(struct node)) ) == NULL)
        {
            printf("malloc error");
            EXIT_FAILURE;
        }
        n->val = num;
		n->left = n->right = NULL;
    } 
	else if (num < n->val) 
			  n->left = add_to_tree(n->left, num);
		 else
			  n->right = add_to_tree(n->right, num);
    
	return n;
}
void print_tree(struct node *n)
{
    if (n != NULL) 
    {
        print_tree(n->left);
        printf("%3d\n", n->val);
        print_tree(n->right);
    }
}
void free_tree(struct node *n)
{
    if (n == NULL) 
        return;
     
    free_tree(n->left);
    free_tree(n->right);
    free(n);
}

/*
run:

  1
 49
 54

*/

 



answered Apr 15, 2016 by avibootz

Related questions

...