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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 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

...