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 create a binary tree in C

1 Answer

0 votes
#include <stdio.h>     
#include <stdlib.h>    

struct Node {
    int n;
    struct Node* left, * right;
};

struct Node* create_node(int n) {
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    if (temp != NULL) {
        temp->n = n;
        temp->left = temp->right = NULL;
    }
    return (temp);
}

void print_tree(struct Node* root) {
    if (root) {
        print_tree(root->left);
        printf("%d ", root->n);
        print_tree(root->right);
    }
}
void free_tree(struct Node* root) {
    if (root == NULL)
        return;

    free_tree(root->left);
    free_tree(root->right);
    free(root);
}

int main()
{
    struct Node* root = create_node(100);

    root->left = create_node(10);
    root->right = create_node(70);
    root->left->left = create_node(80);
    root->left->right = create_node(20);
    root->right->right = create_node(40);
    root->left->left->left = create_node(50);
    root->left->left->right = create_node(30);


    /*
             100
          10     70
       80    20     40
    50    30

    */


    print_tree(root);

    free_tree(root);

    return 0;
}



/*
run:

50 80 30 10 20 100 70 40

*/

 



answered Jun 14, 2023 by avibootz
edited Jun 17, 2023 by avibootz

Related questions

1 answer 153 views
1 answer 151 views
2 answers 217 views
1 answer 152 views
1 answer 167 views
1 answer 91 views
...