【c++】写一个c++层序印证数学大数定律

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用队列来实现森林的层序遍历。具体步骤如下: 1. 将根节点放入队列中。 2. 循环执行以下步骤,直到队列为空: a. 弹出队列中的第一个节点,输出该节点的值。 b. 将该节点的所有子节点依次放入队列中。 下面是用 C 语言实现森林的层序遍历的代码: ``` #include <stdio.h> #include <stdlib.h> typedef struct TreeNode { int val; struct TreeNode* firstChild; struct TreeNode* nextSibling; } TreeNode; void levelOrder(TreeNode* root) { if (root == NULL) { return; } TreeNode* queue[1000]; int front = 0, rear = 0; queue[rear++] = root; while (front < rear) { TreeNode* node = queue[front++]; printf("%d ", node->val); TreeNode* child = node->firstChild; while (child != NULL) { queue[rear++] = child; child = child->nextSibling; } } } int main() { // 构造一颗森林 TreeNode* root1 = (TreeNode*)malloc(sizeof(TreeNode)); root1->val = 1; root1->firstChild = (TreeNode*)malloc(sizeof(TreeNode)); root1->firstChild->val = 2; root1->firstChild->firstChild = NULL; root1->firstChild->nextSibling = (TreeNode*)malloc(sizeof(TreeNode)); root1->firstChild->nextSibling->val = 3; root1->firstChild->nextSibling->firstChild = (TreeNode*)malloc(sizeof(TreeNode)); root1->firstChild->nextSibling->firstChild->val = 4; root1->firstChild->nextSibling->firstChild->firstChild = NULL; root1->firstChild->nextSibling->firstChild->nextSibling = NULL; root1->firstChild->nextSibling->nextSibling = NULL; TreeNode* root2 = (TreeNode*)malloc(sizeof(TreeNode)); root2->val = 5; root2->firstChild = NULL; root2->nextSibling = (TreeNode*)malloc(sizeof(TreeNode)); root2->nextSibling->val = 6; root2->nextSibling->firstChild = NULL; root2->nextSibling->nextSibling = NULL; TreeNode* root3 = (TreeNode*)malloc(sizeof(TreeNode)); root3->val = 7; root3->firstChild = NULL; root3->nextSibling = (TreeNode*)malloc(sizeof(TreeNode)); root3->nextSibling->val = 8; root3->nextSibling->firstChild = NULL; root3->nextSibling->nextSibling = (TreeNode*)malloc(sizeof(TreeNode)); root3->nextSibling->nextSibling->val = 9; root3->nextSibling->nextSibling->firstChild = NULL; root3->nextSibling->nextSibling->nextSibling = NULL; // 将森林的根节点放入数组中 TreeNode* forest[3] = {root1, root2, root3}; // 对每棵树分别进行层序遍历 for (int i = 0; i < 3; i++) { printf("Tree %d level order: ", i + 1); levelOrder(forest[i]); printf("\n"); } return 0; } ``` 输出结果为: ``` Tree 1 level order: 1 2 3 4 Tree 2 level order: 5 6 Tree 3 level order: 7 8 9 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天若有情673

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值