1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| #include <stdio.h> #include <stdlib.h>
// 二叉树节点结构 struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right; };
// 队列结构 struct QueueNode { struct TreeNode* node; struct QueueNode* next; };
// 入队操作 void enqueue(struct QueueNode** front, struct QueueNode** rear, struct TreeNode* node) { struct QueueNode* newQueueNode = (struct QueueNode*)malloc(sizeof(struct QueueNode)); newQueueNode->node = node; newQueueNode->next = NULL;
if (*rear == NULL) { *front = newQueueNode; *rear = newQueueNode; } else { (*rear)->next = newQueueNode; *rear = newQueueNode; } }
// 出队操作 struct TreeNode* dequeue(struct QueueNode** front, struct QueueNode** rear) { if (*front == NULL) { return NULL; }
struct TreeNode* dequeuedNode = (*front)->node; struct QueueNode* temp = *front;
*front = (*front)->next; free(temp);
if (*front == NULL) { *rear = NULL; }
return dequeuedNode; }
// 层序遍历 void levelOrder(struct TreeNode* root) { if (root == NULL) { return; }
struct QueueNode* front = NULL; struct QueueNode* rear = NULL;
enqueue(&front, &rear, root);
while (front != NULL) { struct TreeNode* current = dequeue(&front, &rear); printf("%d ", current->data);
if (current->left != NULL) { enqueue(&front, &rear, current->left); }
if (current->right != NULL) { enqueue(&front, &rear, current->right); } } }
// 创建新的二叉树节点 struct TreeNode* createNode(int data) { struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; }
int main() { // 构建一个二叉树 struct TreeNode* root = createNode(1); root->left = createNode(2); root->right = createNode(3); root->left->left = createNode(4); root->left->right = createNode(5); root->right->right = createNode(6);
// 层序遍历 printf("Level Order Traversal: "); levelOrder(root); printf("\n");
// 释放内存 free(root->left->left); free(root->left->right); free(root->left); free(root->right->right); free(root->right); free(root);
return 0; }
|