二叉树层序遍历 C++函数代码
时间: 2024-05-08 10:19:39 浏览: 111
以下是二叉树层序遍历的C代码:
```c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
void printLevelOrder(struct node* root)
{
if (root == NULL)
return;
struct node* queue[1000];
int front = 0, rear = 0;
queue[rear] = root;
rear++;
while (front < rear)
{
struct node* temp_node = queue[front];
front++;
printf("%d ", temp_node->data);
if (temp_node->left != NULL)
{
queue[rear] = temp_node->left;
rear++;
}
if (temp_node->right != NULL)
{
queue[rear] = temp_node->right;
rear++;
}
}
}
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("层序遍历二叉树输出结果:\n");
printLevelOrder(root);
return 0;
}
```
以上代码实现了二叉树的层序遍历,输出结果为:
层序遍历二叉树输出结果:
1 2 3 4 5
希望能对您有所帮助。
阅读全文