代码如下
#include <stdio.h>
#include <stdlib.h>
struct Node {
int val;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int val) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
//************************************************************
void levelOrderTraversal(struct Node* root) {
if (root == NULL) {
return;
}
struct Node* queue[1000];
int front = 0;
int rear = 0;
queue[rear++] = root;
while (front < rear) {
struct Node* node = queue[front++];
printf("%d ", node->val);
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
}
//************************************************************
int main() {
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
levelOrderTraversal(root);
return 0;
}