用C/C++写一个多节点的树
时间: 2024-06-11 17:05:46 浏览: 18
以下是一个基于指针的多节点树的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHILDREN 10
typedef struct TreeNode {
int val;
int num_children;
struct TreeNode* children[MAX_CHILDREN];
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode));
node->val = val;
node->num_children = 0;
return node;
}
void addChild(TreeNode* parent, TreeNode* child) {
if (parent->num_children >= MAX_CHILDREN) {
printf("Cannot add more children to node with value %d\n", parent->val);
return;
}
parent->children[parent->num_children++] = child;
}
void printTree(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d: [", root->val);
for (int i = 0; i < root->num_children; i++) {
printf("%d, ", root->children[i]->val);
}
printf("]\n");
for (int i = 0; i < root->num_children; i++) {
printTree(root->children[i]);
}
}
int main() {
TreeNode* root = createNode(1);
TreeNode* child1 = createNode(2);
TreeNode* child2 = createNode(3);
addChild(root, child1);
addChild(root, child2);
TreeNode* grandchild1 = createNode(4);
addChild(child1, grandchild1);
printTree(root);
return 0;
}
```
在这个实现中,节点被定义为一个包含值和孩子节点数组的结构体。孩子节点数组的大小被定义为预处理器常量`MAX_CHILDREN`,可以根据需要更改。`createNode`函数用于创建一个新的节点,并返回一个指向该节点的指针。`addChild`函数用于将一个节点添加为另一个节点的孩子节点。`printTree`函数用于遍历整个树,并打印每个节点的值和它的孩子节点。在`main`函数中,我们创建了一个根节点和两个子节点,并将其中一个子节点添加为另一个子节点的父节点。然后,我们创建了一个孙子节点,并将其添加为一个子节点的孩子节点。最后,我们打印整个树。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)