Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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

2 answers 217 views
1 answer 167 views
1 answer 109 views
109 views asked Jun 14, 2023 by avibootz
1 answer 153 views
...