以下是一个使用C语言编写的程序,实现了根据输入节点打印出其所有下层节点的功能:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NODES 100

typedef struct Node {
    char name[20];
    struct Node *parent;
} Node;

Node* createNode(char* name) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    strcpy(newNode->name, name);
    newNode->parent = NULL;
    return newNode;
}

Node* findParent(Node* nodes[], int count, char* name) {
    for (int i = 0; i < count; i++) {
        if (strcmp(nodes[i]->name, name) == 0) {
            return nodes[i];
        }
    }
    return NULL;
}

void printSubNodes(Node* node, Node* nodes[], int count, int depth) {
    for (int i = 0; i < count; i++) {
        if (nodes[i]->parent == node) {
            for (int j = 0; j < depth; j++) {
                printf("  "); // 根据深度缩进
            }
            printf('%s\n', nodes[i]->name);
            printSubNodes(nodes[i], nodes, count, depth + 1);
        }
    }
}

int main() {
    Node* nodes[MAX_NODES];
    int count = 0;

    // 构建树结构
    nodes[count++] = createNode("西安");
    nodes[count++] = createNode("陕西");
    nodes[count++] = createNode("江西");
    nodes[count++] = createNode("中国");
    nodes[count++] = createNode("泰国");
    nodes[count++] = createNode("亚洲");

    // 设置父节点
    nodes[0]->parent = NULL;
    nodes[1]->parent = findParent(nodes, count, "西安");
    nodes[2]->parent = findParent(nodes, count, "陕西");
    nodes[3]->parent = findParent(nodes, count, "中国");
    nodes[4]->parent = findParent(nodes, count, "亚洲");
    nodes[5]->parent = findParent(nodes, count, "亚洲");

    char input[20];
    printf("请输入节点名称:");
    scanf("%s", input);

    Node* targetNode = NULL;
    for (int i = 0; i < count; i++) {
        if (strcmp(nodes[i]->name, input) == 0) {
            targetNode = nodes[i];
            break;
        }
    }

    if (targetNode != NULL) {
        printf("节点 %s 的下层节点有:\n", targetNode->name);
        printSubNodes(targetNode, nodes, count, 1);
    } else {
        printf("未找到节点 %s\n", input);
    }

    // 释放内存
    for (int i = 0; i < count; i++) {
        free(nodes[i]);
    }

    return 0;
}

在上述代码中,我们首先定义了一个Node结构体,表示树节点。每个节点包含一个名称和一个指向父节点的指针。

然后,我们定义了一个createNode函数,用于创建一个新的节点,并根据传入的名称进行初始化。

接着,我们定义了一个findParent函数,用于在节点数组中查找指定名称的父节点。该函数会遍历节点数组,比较节点的名称是否与传入的名称相等,如果找到了匹配的节点,则返回该节点的指针,否则返回NULL

然后,我们定义了一个printSubNodes函数,用于递归地打印指定节点的所有下层节点。该函数会遍历节点数组,找到所有父节点为指定节点的节点,并打印出这些节点的名称。然后,对于每个下层节点,再调用printSubNodes函数进行递归打印。

main函数中,我们首先创建了一些节点,并设置它们的父节点关系,构建了一棵树。

然后,程序会要求用户输入一个节点名称。程序会遍历节点数组,找到与输入名称匹配的节点,并将其赋值给targetNode变量。

接着,程序会判断targetNode是否为空。如果为空,说明未找到匹配的节点,程序会打印出相应的提示信息。如果不为空,说明找到了节点,程序会打印出该节点的名称,并调用printSubNodes函数打印出该节点的所有下层节点。

最后,程序会释放之前动态分配的内存,释放节点数组中的每个节点。

注意:上述代码仅作为参考实现,可能存在一些不足之处,如未对输入进行严格的错误处理等。在实际使用中,可以根据需要进行适当的修改和完善。

C语言树结构实现:打印节点下层节点

原文地址: https://www.cveoy.top/t/topic/cuoG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录