层序遍历二叉树(不借助vector或deque,用C语言实现)

时间:2021-06-29 11:22:32

前面几篇文章中,我们对二叉树的层序遍历和层序打印都是借助vector或deque来实现的,本文只通过C语言来实现,代码如下:

#include <iostream>
using namespace std;
#define MAXSIZE 1000

typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}BiNode, *BiTree;


// 先序建立二叉树 (输入时,按先序次序输入二叉树中结点的值,以 # 字符表示空树)
BiTree createBiTree()
{
BiTree T;

char c;
scanf("%c", &c);

if (c == '#')
T = NULL;
else
{
T = new BiNode; // 或 T = (BiTree)malloc(sizeof(BiNode));
T->data = c;

T->lchild = createBiTree();
T->rchild = createBiTree();
}

return T;

}


// 二叉树的层序遍历
void LevelOrderTraverse(BiTree T)
{
if (T == NULL) return;

BiTree q[MAXSIZE];
q[0] = T;

int front = 0;
int rear = 1;

while (front < rear)
{
printf("%c ", q[front]->data);

if (q[front]->lchild)
q[rear++] = q[front]->lchild;

if (q[front]->rchild)
q[rear++] = q[front]->rchild;

++front;
}
}


// 二叉树的分层打印
void PrintTreeByLevel(BiTree T)
{
if (T == NULL) return;

BiTree q[MAXSIZE];
q[0] = T;

int front = 0;
int rear = 1;

while (front < rear)
{
int last = rear;

while (front < last)
{
printf("%c ", q[front]->data);

if (q[front]->lchild)
q[rear++] = q[front]->lchild;

if (q[front]->rchild)
q[rear++] = q[front]->rchild;

++front;
}

printf("\n");
}


}


int main(int argc, const char * argv[]) {

BiTree T = createBiTree(); // 建立

LevelOrderTraverse(T); // 二叉树的层序遍历

printf("\n-----------------\n");

PrintTreeByLevel(T); // 二叉树的分层打印


return 0;
}