Binary tree

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.8 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

// Define the structure for each node in the binary tree
struct node {
    int data;
    struct node* left;
    struct node* right;
};

// Function to create a new node in the binary tree
struct node* newNode(int data) {
    struct node* node = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Function to insert a new node in the binary tree
struct node* insert(struct node* node, int data) {
    // If the tree is empty, return a new node
    if (node == NULL) {
        return newNode(data);
    } 
    // Otherwise, recur down the tree
    else {
        if (data <= node->data) {
            node->left = insert(node->left, data);
        }
        else {
            node->right = insert(node->right, data);
        }
        return node;
    }
}

// Function to traverse the binary tree in-order (left-root-right)
void traverse(struct node* node) {
    if (node != NULL) {
        traverse(node->left);
        printf("%d ", node->data);
        traverse(node->right);
    }
}

// Main function to test the binary tree implementation
int main() {
    struct node* root = NULL;
    int num, data;
    
    // Prompt the user to enter the number of nodes
    printf("Enter the number of nodes: ");
    scanf("%d", &num);
    
    // Prompt the user to enter the data for each node and insert it into the binary tree
    for (int i = 0; i < num; i++) {
        printf("Enter data for node %d: ", i+1);
        scanf("%d", &data);
        root = insert(root, data);
    }
    
    // Traverse the binary tree in-order and print the data for each node
    printf("\nIn-order traversal: ");
    traverse(root);
    
    return 0;
}