非递归实现二叉树的层次遍历:
想了大半个小时终于写出来了,通过自己思考出来的还是有很大成就感。学数据结构就是通过自己思考和参考而学得更深。
思路:层次遍历就是一层一层遍历,这棵二叉树的层次遍历序列为5 2 11 3 6 4 8,先上到下,先左到右。实现层次遍历用队列比较方便,因为是先进先出(FIFO)。首先把5入队,然后再输出队首元素,并且把队首元素的左结点和右结点入队(如果有的话),以此类推,输出的序列就是层次遍历啦~~~
/* 完整代码 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MaxSize 100
struct tree {
int data;
struct tree* left;
struct tree* right;
};
typedef struct queue{
struct tree* numQ[MaxSize];
int front;
int rear;
}Queue;
Queue Q;
void initilize() { //初始化队列
Q.front = 0;
Q.rear = 0;
}
void Push(struct tree* root) { //入队
Q.numQ[++Q.rear]