层序遍历
Coddy AVL 树:数据结构系列 #10 课程的第 15 课,共 16 课。
层序遍历(也称为广度优先遍历)按行访问树:先访问根节点,然后访问它的两个子节点,再访问全部四个孙节点,依此类推,而不是像中序遍历或前序遍历那样优先深入。
实现这种遍历的标准方法是使用队列:先将根节点放入队列,然后重复执行以下操作:移除队首节点,记录它的值,并将它的子节点(先左后右)加入队尾。
挑战
简单编写一个函数 levelOrder(tree),按层返回树中的所有值,每层从左到右排列。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "avltree.h"
#include "solution.h"
int main(void) {
AVLTree* tree = AVLTree_create();
char line1[4096];
fgets(line1, sizeof(line1), stdin);
char* tok = strtok(line1, " \n");
while (tok != NULL) {
AVLTree_insert(tree, atoi(tok));
tok = strtok(NULL, " \n");
}
int result[1024];
int resultCount = levelOrder(tree, result);
for (int i = 0; i < resultCount; i++) {
if (i > 0) printf(" ");
printf("%d", result[i]);
}
printf("\n");
return 0;
}
AVL 树:数据结构系列 #10中的所有课
自己练习: C 在线编译器