二叉树的层次遍历的C++代码
时间: 2023-06-03 20:04:50 浏览: 94
以下是二叉树层次遍历的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
//定义树节点的结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
//定义队列节点的结构体
typedef struct QueueNode {
TreeNode *treenode;
struct QueueNode *next;
} QueueNode;
//初始化队列
QueueNode* initQueue() {
QueueNode *head = (QueueNode *) malloc(sizeof(QueueNode));
head->next = NULL;
return head;
}
//入队
void enqueue(QueueNode *head, TreeNode *treenode) {
QueueNode *p = head;
while (p->next != NULL) {
p = p->next;
}
QueueNode *q = (QueueNode *) malloc(sizeof(QueueNode));
q->treenode = treenode;
q->next = NULL;
p->next = q;
}
//出队
TreeNode* dequeue(QueueNode *head) {
if (head->next == NULL) {
return NULL;
}
QueueNode *p = head->next;
TreeNode *treenode = p->treenode;
head->next = p->next;
free(p);
return treenode;
}
//层次遍历方法
void levelTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
QueueNode *queue = initQueue();
enqueue(queue, root);
while (queue->next != NULL) {
TreeNode *treenode = dequeue(queue);
printf("%d ", treenode->val);
if (treenode->left != NULL) {
enqueue(queue, treenode->left);
}
if (treenode->right != NULL) {
enqueue(queue, treenode->right);
}
}
}
int main() {
// 创建二叉树
TreeNode *root = (TreeNode *) malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode *) malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode *) malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = (TreeNode *) malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right = (TreeNode *) malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->right->left = (TreeNode *) malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->right = (TreeNode *) malloc(sizeof(TreeNode));
root->right->right->val = 7;
// 层次遍历
levelTraversal(root);
return 0;
}
```
该代码可以实现二叉树的层次遍历,使用队列作为辅助数据结构,遍历时按照层次顺序出队并访问队首元素,然后将它的左右子树分别入队。
阅读全文