用C/C++写一个多节点的树的例子
时间: 2024-05-11 09:14:06 浏览: 23
以下是一个基本的多节点树的例子,使用C语言编写:
```c
#include <stdio.h>
#include <stdlib.h>
// 树节点结构体
typedef struct TreeNode {
int data;
struct TreeNode *firstChild;
struct TreeNode *nextSibling;
} TreeNode;
// 创建一个新节点
TreeNode* createNode(int data) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = data;
node->firstChild = NULL;
node->nextSibling = NULL;
return node;
}
// 添加子节点
void addChild(TreeNode *parent, TreeNode *child) {
if (parent->firstChild == NULL) {
parent->firstChild = child;
} else {
TreeNode *sibling = parent->firstChild;
while (sibling->nextSibling != NULL) {
sibling = sibling->nextSibling;
}
sibling->nextSibling = child;
}
}
// 遍历树
void traverse(TreeNode *node) {
if (node != NULL) {
printf("%d ", node->data);
traverse(node->firstChild);
traverse(node->nextSibling);
}
}
int main() {
// 创建节点
TreeNode *root = createNode(1);
TreeNode *node2 = createNode(2);
TreeNode *node3 = createNode(3);
TreeNode *node4 = createNode(4);
TreeNode *node5 = createNode(5);
TreeNode *node6 = createNode(6);
TreeNode *node7 = createNode(7);
TreeNode *node8 = createNode(8);
// 添加子节点
addChild(root, node2);
addChild(root, node3);
addChild(node2, node4);
addChild(node2, node5);
addChild(node3, node6);
addChild(node4, node7);
addChild(node5, node8);
// 遍历树
traverse(root);
return 0;
}
```
这个例子创建了一个树,根节点为1,有两个子节点2和3,2有两个子节点4和5,3有一个子节点6,4有一个子节点7,5有一个子节点8。遍历树的结果是1 2 4 7 5 8 3 6。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)