层次遍历的概念
层次遍历,也称广度优先遍历,是一种遍历树形结构的算法,它从根节点开始逐层遍历每个节点,并按照从左到右的顺序访问同一层的节点,直到遍历完整棵树。
层次遍历通常使用队列来实现,具体步骤如下:
1. 将根节点入队;
2. 当队列不为空时,重复以下步骤:
1. 出队队首节点,并访问该节点;
2. 将该节点的左右节点依次入队;
3. 遍历结束。
层次遍历的特点是按照层级顺序遍历每个节点,因此可以用来查找某个节点的层数、查找树的宽度等。
下图是一个二叉树
层次遍历为:1 2 3 4 5 6 7
1
/ \
2 3
/ \ / \
4 5 6 7
详细代码:
struct Node { //二叉树节点结构
int data;
struct Node* left;
struct Node* right;
};
struct Nodelist { //队列的节点结构
struct Node* data; //因为数据是二叉树的,所以设置为 Node
struct Node* next;
};
struct Nodelist* front = NULL; //队列开头指针
struct Nodelist* rear = NULL; //队列结尾指针
void push(struct Node* temp) //入队
{
struct Nodelist* tmp = (struct Node*)malloc(sizeof(struct Node)); //存放二叉树的链表节点
tmp->data = temp; //二叉树的节点数据
tmp->next = NULL;
if (front == NULL && rear == NULL) //队列首节点
{
front = tmp;
rear = tmp;
}
else
{
rear->next = tmp;
rear = tmp;
}
}
void pop() //出队
{
struct Nodelist* temp = front; //用来释放队列中删除的节点
if (front == NULL && rear == NULL) //队列为空
{
printf("error!");
return;
}
front = temp->next;
free(temp);
}
struct Node* newspot(int n) //二叉树新节点
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = n;
temp->left = NULL;
temp->right = NULL;
return temp;
}
struct Node* Insert(struct Node* root, int x) //二叉树插入数据
{
if (root == NULL)
{
root = newspot(x);
}
else if (root->data < x)
{
root->right = Insert(root->right, x);
}
else
{
root->left = Insert(root->left, x);
}
return root;
}
void traverse(struct Node* root) //层次遍历二叉树
{
struct Node* head = NULL;
if (root == NULL) //空树返回
{
return;
}
push(root); //根节点入队
while (front != NULL) //队列内不为空
{
head = front->data; //指向队列中元素的data
printf("%d ", head->data);
if (head->left != NULL) //left指针不为空
{
push(head->left); //入队
}
if (head->right != NULL)
{
push(head->right);
}
pop(); //出队
}
}
int main()
{
struct Node* root = NULL; //根节点
root = Insert(root,8);
root = Insert(root,9);
root = Insert(root,6);
root = Insert(root,3);
root = Insert(root,10);
root = Insert(root,7);
root = Insert(root, 12);
traverse(root);
return 0;
}
小白代码,仅供参考。
1241

被折叠的 条评论
为什么被折叠?



