编辑代码

#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 () {
    //JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
    Ptree tree;
    initTree(&tree); // 初始化树

    // 添加节点
    int rootIndex = addNode(&tree, 1, -1); // 根节点
    int child1Index = addNode(&tree, 2, rootIndex); // 子节点 1
    int child2Index = addNode(&tree, 3, rootIndex); // 子节点 2
    int child3Index = addNode(&tree, 4, child1Index); // 子节点 1 的子节点
  

    printTree(&tree, rootIndex, 0);;
    return 0;
}