C语言实现树结构并打印节点下层节点
#include <stdio.h> #include <stdlib.h> #include <string.h>
typedef struct Node { char val; struct Node *child; struct Node *sibling; } Node;
Node *createNode(char val) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->val = val; newNode->child = NULL; newNode->sibling = NULL; return newNode; }
Node *findNode(Node *root, char val) { if (root == NULL) { return NULL; } if (root->val == val) { return root; } Node *childResult = findNode(root->child, val); if (childResult != NULL) { return childResult; } Node *siblingResult = findNode(root->sibling, val); if (siblingResult != NULL) { return siblingResult; } return NULL; }
void printChildren(Node *node) { Node *child = node->child; while (child != NULL) { printf('%c\n', child->val); child = child->sibling; } }
int main() { int n; scanf("%d", &n);
Node *root = NULL;
Node **nodes = (Node **)malloc(n * sizeof(Node *));
for (int i = 0; i < n; i++) {
char val, parent;
scanf(" %c %c", &val, &parent);
if (root == NULL) {
root = createNode(parent);
nodes[i] = root;
}
Node *parentNode = findNode(root, parent);
if (parentNode == NULL) {
printf("Invalid input: parent node not found\n");
return 0;
}
Node *newNode = createNode(val);
if (parentNode->child == NULL) {
parentNode->child = newNode;
} else {
Node *sibling = parentNode->child;
while (sibling->sibling != NULL) {
sibling = sibling->sibling;
}
sibling->sibling = newNode;
}
nodes[i] = newNode;
}
char target;
scanf(" %c", &target);
Node *targetNode = findNode(root, target);
if (targetNode == NULL) {
printf("Invalid input: target node not found\n");
return 0;
}
printChildren(targetNode);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/crFc 著作权归作者所有。请勿转载和采集!