#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODES 100
#define NIL -1
typedef struct TreeNode {
char value;
int parent;
struct TreeNode* firstChild;
struct TreeNode* nextSibling;
} TreeNode;
TreeNode* createNode(char value) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->value = value;
node->parent = NIL;
node->firstChild = NULL;
node->nextSibling = NULL;
return node;
}
void buildParentArray(TreeNode* nodes[], int parent[], int n) {
for (int i = 0; i < n; i++) {
if (nodes[i]->parent != NIL) {
parent[i] = nodes[i]->parent;
} else {
parent[i] = -1;
}
}
}
void printParentDegreeFirstChild(TreeNode* nodes[], int n) {
printf("Value\tParent\tDegree\tFirst Child\n");
for (int i = 0; i < n; i++) {
char parentVal = (nodes[i]->parent == NIL) ? 'N' : nodes[nodes[i]->parent]->value;
int degree = 0;
char firstChildVal = 'N';
TreeNode* child = nodes[i]->firstChild;
if (child) {
firstChildVal = child->value;
while (child) {
degree++;
child = child->nextSibling;
}
}
printf("%c\t%c\t%d\t%c\n", nodes[i]->value, parentVal, degree, firstChildVal);
}
}
int main() {
char input[MAX_NODES];
printf("Enter tree nodes in level order (use # for empty nodes):\n");
scanf("%s", input);
int n = strlen(input);
TreeNode* nodes[MAX_NODES];
int parent[MAX_NODES];
int nodeIndex = 0;
int queue[MAX_NODES];
int front = 0, rear = 0;
for (int i = 0; i < n; i++) {
if (input[i] != '#') {
nodes[nodeIndex] = createNode(input[i]);
queue[rear++] = nodeIndex;
nodeIndex++;
} else {
queue[rear++] = NIL;
}
}
int index = 0;
while (front < rear && index < n) {
int current = queue[front++];
if (current != NIL) {
TreeNode* currentNode = nodes[current];
int leftChildIndex = 2 * index + 1;
int rightChildIndex = 2 * index + 2;
if (leftChildIndex < n && queue[leftChildIndex] != NIL) {
TreeNode* leftChild = nodes[queue[leftChildIndex]];
leftChild->parent = current;
currentNode->firstChild = leftChild;
}
if (rightChildIndex < n && queue[rightChildIndex] != NIL) {
TreeNode* rightChild = nodes[queue[rightChildIndex]];
rightChild->parent = current;
if (currentNode->firstChild) {
currentNode->firstChild->nextSibling = rightChild;
} else {
currentNode->firstChild = rightChild;
}
}
}
index++;
}
buildParentArray(nodes, parent, nodeIndex);
printParentDegreeFirstChild(nodes, nodeIndex);
return 0;
}