You are on page 1of 4

#include <stdio.

h>

#include <stdlib.h>

#include <iostream>

#define MAX_CHILD 2

struct Node

char id[50];

char person_name[50];

char school_name[50];

struct Node* children[MAX_CHILD];

};

struct Node* createNode(char id[], char person_name[], char school_name[])

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

if (newNode == NULL)

printf("Memory allocation failed.\n");

exit(1);

strcpy(newNode->id, id);

strcpy(newNode->person_name, person_name);

strcpy(newNode->school_name, school_name);

for (int i = 0; i < MAX_CHILDREN; i++)

newNode->children[i] = NULL;

}
return newNode;

void addChild(struct Node* parent, struct Node* child)

for (int i = 0; i < MAX_CHILDREN; i++)

if (parent->children[i] == NULL)

parent->children[i] = child;

break;

void buildTree(struct Node* root, int totalNodes, int* nodesCount)

char input[256];

while (*nodesCount < totalNodes)

printf ("Enter node information (ID$Person Name$School Name$Child ID 1$Child ID 2#): ");

fgets(input, sizeof(input), stdin);

if (input[0] == '#' || input[0] == '\n') {

break;

char id[50], person_name[50], school_name[50], child1[50], child2[50];

sscanf(input, "%[^$]$%[^$]$%[^$]$%[^$]$%[^$]#", id, person_name, school_name, child1,


child2);
struct Node* newNode = createNode(id, person_name, school_name);

addChild(root, newNode);

if (child1[0] != '\0') {

struct Node* childNode1 = createNode(child1, "", "");

addChild(newNode, childNode1);

(*nodesCount)++;

if (child2[0] != '\0') {

struct Node* childNode2 = createNode(child2, "", "");

addChild(newNode, childNode2);

(*nodesCount)++;

(*nodesCount)++;

void displayTree(struct Node* root) {

if (root != NULL) {

printf("ID: %s - Person: %s - School: %s\n", root->id, root->person_name, root->school_name);

for (int i = 0; i < MAX_CHILDREN; i++) {

displayTree(root->children[i]);

int main() {

int totalNodes, nodesCount = 0;


printf("Enter the total number of nodes: ");

scanf("%d", &totalNodes);

getchar(); // Clearing the input buffer

char rootId[50] = "ROOT";

char rootPerson[50] = "Root Person";

char rootSchool[50] = "Root School";

struct Node* root = createNode(rootId, rootPerson, rootSchool);

buildTree(root, totalNodes, &nodesCount);

printf("Tree created:\n");

displayTree(root);

return 0;

You might also like