#include <stdio.h>
#include <stdlib.h>
typedef struct TREE {
char data;
struct TREE* Lchild;
struct TREE* Rchild;
}TREE,*PTREE;
typedef struct QUEUE {
struct TREE* data;
struct QUEUE* next;
}QUEUE,*PQUEUE;
PQUEUE init() {
PQUEUE Q = (PQUEUE)malloc(sizeof(QUEUE));
Q->data = NULL;
Q->next = NULL;
return Q;
}
int isempty(PQUEUE Q) {
if (Q->next == NULL) {
return 1;
}
else
{
return 0;
}
}
void enqueue(PQUEUE Q, PTREE T) {
PQUEUE temp = Q;
while (temp->next) {
temp = temp->next;
}
PQUEUE NEWNODE = (PQUEUE)malloc(sizeof(QUEUE));
NEWNODE->data = T;
NEWNODE->next = temp->next;
temp->next = NEWNODE;
}
PTREE dequeue(PQUEUE Q) {
if (isempty(Q)) {
return NULL;
}
PQUEUE temp = Q->next;
Q->next = temp->next;
return temp->data;
}
void create(TREE** T) {
char data;
scanf("%c", &data);
getchar();
if (data != '#') {
*T = (PTREE)malloc(sizeof(TREE));
(*T)->data = data;
create(&(*T)->Lchild);
create(&(*T)->Rchild);
}
else
{
*T = NULL;
}
}
void Preorder(PTREE T) {
if (T) {
printf("%c", T->data);
Preorder(T->Lchild);
Preorder(T->Rchild);
}
}
void Level(PQUEUE Q,PTREE T) {
enqueue(Q, T);
while (!isempty(Q)) {
PTREE node = dequeue(Q);
printf("%c", node->data);
if (node->Lchild) {
enqueue(Q, node->Lchild);
}
if (node->Rchild) {
enqueue(Q, node->Rchild);
}
}
}
int main() {
PTREE T;
create(&T);
PQUEUE Q = init();
Level(Q, T);
//Preorder(T);
return 0;
}
二叉树的层次遍历
最新推荐文章于 2024-08-30 18:33:22 发布