SYBCom(CA) DS Practical Slip 6 Q.B

Write C programs to implement create and display operation for binary tree.

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

// Structure of a Binary Tree Node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

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

// Function to create a binary tree
struct Node* createTree() {
    int data;
    printf("Enter data (-1 for no node): ");
    scanf("%d", &data);

    if (data == -1)
        return NULL;

    struct Node* node = createNode(data);

    printf("Enter left child of %d:\n", data);
    node->left = createTree();

    printf("Enter right child of %d:\n", data);
    node->right = createTree();

    return node;
}

// Function to display binary tree (Inorder Traversal)
void inorderTraversal(struct Node* root) {
    if (root == NULL)
        return;

    inorderTraversal(root->left);
    printf("%d ", root->data);
    inorderTraversal(root->right);
}

// Main function
int main() {
    struct Node* root = NULL;

    printf("Create Binary Tree:\n");
    root = createTree();

    printf("Inorder traversal of the binary tree:\n");
    inorderTraversal(root);

    return 0;
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top