用C++ 写出森林的层序遍历
时间: 2024-05-15 19:18:26 浏览: 20
当然,我可以为您解答这个问题。以下是用C语言编写森林的层序遍历的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode *firstchild;
struct TreeNode *nextsibling;
};
void levelOrder(struct TreeNode *root) {
if (!root) {
return;
}
struct TreeNode *queue[100], *temp;
int front = 0, rear = 0;
queue[rear] = root;
rear++;
while (front != rear) {
temp = queue[front];
front++;
printf("%d ", temp->data);
if (temp->firstchild) {
queue[rear] = temp->firstchild;
rear++;
}
temp = temp->nextsibling;
while (temp) {
queue[rear] = temp;
rear++;
temp = temp->nextsibling;
}
}
}
int main() {
struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->data = 1;
struct TreeNode *firstchild1 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
firstchild1->data = 2;
struct TreeNode *nextsibling1 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
nextsibling1->data = 3;
struct TreeNode *firstchild2 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
firstchild2->data = 4;
struct TreeNode *firstchild3 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
firstchild3->data = 5;
root->firstchild = firstchild1;
firstchild1->nextsibling = nextsibling1;
nextsibling1->firstchild = firstchild2;
firstchild2->nextsibling = firstchild3;
firstchild1->firstchild = NULL;
nextsibling1->nextsibling = NULL;
firstchild2->firstchild = NULL;
firstchild3->nextsibling = NULL;
firstchild3->firstchild = NULL;
levelOrder(root);
free(firstchild3);
free(nextsibling1);
free(firstchild1);
free(firstchild2);
free(root);
return 0;
}
```
您可以将根节点替换为您森林中的任意一个节点,然后调用`levelOrder`函数即可得到该节点的层序遍历序列。
相关推荐
![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)