#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct CTNode{
int childIndex;
struct CTNode* next;
} CTNode;
typedef struct PTNode {
int data;
int parent;
CTNode* firstChild;
} PTNode;
typedef struct {
PTNode nodes[MAX_SIZE];
int size;
} Ptree;
void initTree(Ptree *tree){
tree->size=0;
}
int addNode(Ptree *tree,int value, int parentIndex){
int newIndex = tree->size;
tree->nodes[newIndex].data = value;
tree->nodes[newIndex].parent = parentIndex;
tree->nodes[newIndex].firstChild = NULL;
tree->size++;
if (parentIndex != -1) {
CTNode* newChild = (CTNode*)malloc(sizeof(CTNode));
newChild->childIndex = newIndex;
newChild->next = NULL;
if (tree->nodes[parentIndex].firstChild == NULL) {
tree->nodes[parentIndex].firstChild = newChild;
} else {
CTNode* sibling = tree->nodes[parentIndex].firstChild;
while (sibling->next != NULL) {
sibling = sibling->next;
}
sibling->next = newChild;
}
}
return newIndex;
}
void printTree(Ptree* tree, int index, int level) {
if (index < 0 || index >= tree->size) return;
for (int i = 0; i < level; i++) {
printf(" ");
}
printf("Node Value: %d\n", tree->nodes[index].data);
printf("parent Value: %d\n", tree->nodes[index].parent);
CTNode* child = tree->nodes[index].firstChild;
while (child != NULL) {
printTree(tree, child->childIndex, level + 1);
child = child->next;
}
}
int main () {
Ptree tree;
initTree(&tree);
int rootIndex = addNode(&tree, 1, -1);
int child1Index = addNode(&tree, 2, rootIndex);
int child2Index = addNode(&tree, 3, rootIndex);
int child3Index = addNode(&tree, 4, child1Index);
printTree(&tree, rootIndex, 0);;
return 0;
}