用c++实现一个多叉树
时间: 2023-05-19 19:06:55 浏览: 197
好的,我可以回答这个问题。以下是一个简单的多叉树的 C 代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHILDREN 10
typedef struct TreeNode {
int value;
struct TreeNode* children[MAX_CHILDREN];
int num_children;
} TreeNode;
TreeNode* create_node(int value) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->value = value;
node->num_children = 0;
return node;
}
void add_child(TreeNode* parent, TreeNode* child) {
if (parent->num_children >= MAX_CHILDREN) {
printf("Error: too many children\n");
return;
}
parent->children[parent->num_children++] = child;
}
void print_tree(TreeNode* root) {
printf("%d", root->value);
if (root->num_children > 0) {
printf("(");
for (int i = 0; i < root->num_children; i++) {
print_tree(root->children[i]);
if (i < root->num_children - 1) {
printf(",");
}
}
printf(")");
}
}
int main() {
TreeNode* root = create_node(1);
TreeNode* child1 = create_node(2);
TreeNode* child2 = create_node(3);
TreeNode* grandchild1 = create_node(4);
TreeNode* grandchild2 = create_node(5);
add_child(root, child1);
add_child(root, child2);
add_child(child1, grandchild1);
add_child(child1, grandchild2);
print_tree(root);
return 0;
}
```
这个代码实现了一个简单的多叉树,可以通过 create_node 函数创建一个节点,通过 add_child 函数将一个节点添加为另一个节点的子节点,通过 print_tree 函数打印整个树的结构。