C语言树结构:打印节点的所有下层节点
以下是使用C语言编写的代码,实现了打印树中给定节点的所有下层节点的功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义树节点结构体
typedef struct Node {
    char value[10];
    struct Node* children[100];
    int numChildren;
    struct Node* parent;
} Node;
// 创建新的节点
Node* createNode(char value[]) {
    Node* node = (Node*)malloc(sizeof(Node));
    strcpy(node->value, value);
    node->numChildren = 0;
    node->parent = NULL;
    return node;
}
// 在节点上添加子节点
void addChild(Node* parent, Node* child) {
    parent->children[parent->numChildren] = child;
    parent->numChildren++;
    child->parent = parent;
}
// 打印节点的所有下层节点
void printChildren(Node* node) {
    for (int i = 0; i < node->numChildren; i++) {
        printf('%s
', node->children[i]->value);
    }
}
int main() {
    int n;
    scanf('%d', &n);
    Node* nodes[100];
    for (int i = 0; i < n; i++) {
        char parent[10], value[10];
        scanf('%s %s', value, parent);
        Node* node = createNode(value);
        nodes[i] = node;
        if (i != 0) {
            int parentIndex = -1;
            for (int j = 0; j < i; j++) {
                if (strcmp(nodes[j]->value, parent) == 0) {
                    parentIndex = j;
                    break;
                }
            }
            if (parentIndex != -1) {
                addChild(nodes[parentIndex], node);
            }
        }
    }
    char targetValue[10];
    scanf('%s', targetValue);
    int targetIndex = -1;
    for (int i = 0; i < n; i++) {
        if (strcmp(nodes[i]->value, targetValue) == 0) {
            targetIndex = i;
            break;
        }
    }
    if (targetIndex != -1) {
        printChildren(nodes[targetIndex]);
    }
    return 0;
}
该代码使用C语言定义了树节点结构体,并通过createNode函数创建新的节点,addChild函数添加子节点,printChildren函数打印给定节点的所有下层节点。在main函数中,代码首先读取输入的树节点信息,构建树结构,然后读取目标节点的值,并打印其所有下层节点。
原文地址: https://www.cveoy.top/t/topic/csot 著作权归作者所有。请勿转载和采集!