二叉树的广度优先遍历c语言实现
时间: 2023-06-04 08:02:51 浏览: 160
c语言实现二叉树的遍历
5星 · 资源好评率100%
当然可以回答,以下是二叉树广度优先遍历的C语言实现代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 100
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
void breadthFirstTraversal(TreeNode* root) {
if (root == NULL) return;
TreeNode* queue[MAX_QUEUE_SIZE];
int front = 0;
int rear = 0;
queue[rear++] = root;
while (front != rear) {
TreeNode* current = queue[front++];
printf("%d ", current->data);
if (current->left != NULL) queue[rear++] = current->left;
if (current->right != NULL) queue[rear++] = current->right;
}
}
int main() {
TreeNode* root = (TreeNode*) malloc(sizeof(TreeNode));
root->data = 1;
root->left = (TreeNode*) malloc(sizeof(TreeNode));
root->left->data = 2;
root->right = (TreeNode*) malloc(sizeof(TreeNode));
root->right->data = 3;
root->left->left = (TreeNode*) malloc(sizeof(TreeNode));
root->left->left->data = 4;
root->left->right = (TreeNode*) malloc(sizeof(TreeNode));
root->left->right->data = 5;
root->right->left = (TreeNode*) malloc(sizeof(TreeNode));
root->right->left->data = 6;
root->right->right = (TreeNode*) malloc(sizeof(TreeNode));
root->right->right->data = 7;
breadthFirstTraversal(root);
return 0;
}
```
阅读全文