AllFun.h
#include <stdio.h>
#include <stdlib.h> // malloc()
#include <stddef.h> // NULL
#define MaxSize 10
typedef int ElemType;
typedef struct node {
ElemType data;
struct node* lchild, * rchild;
} *BiTNode;
typedef struct stack {
BiTNode PArray[MaxSize];
int top;
} Stack;
typedef struct queue {
BiTNode PArray[MaxSize];
int front, rear;
} Queue;
BiTNode create();
void InvertLevel(BiTNode T);
MainFunc.c
#include "AllFun.h"
int main(int argc, char* argv[])
{
BiTNode T;
T = create();
InvertLevel(T);
return 0;
}
OtheFunc.c
#include "AllFun.h"
BiTNode newNode(ElemType x)
{
BiTNode T = (BiTNode)malloc(sizeof(struct node));
if (T) {
T->data = x;
T->lchild = T->rchild = NULL;
}
return T;
}
void insert(BiTNode* T, ElemType x)
{
if (*T == NULL) {
*T = newNode(x);
return;
}
if (x < (*T)->data) {
insert(&(*T)->lchild, x);
}
else {
insert(&(*T)->rchild, x);
}
}
BiTNode create()
{
ElemType num[MaxSize];
BiTNode T = NULL;
for (int i = 0; i < MaxSize; ++i) {
num[i] = ' ';
}
printf("Enter some value to create a binary search tree: ");
for (int i = 0; i < MaxSize; ++i) {
scanf_s("%d", &num[i]);
insert(&T, num[i]);
}
return T;
}
InitStack(Stack* s)
{
s->top = -1;
}
InitQueue(Queue* Q)
{
Q->front = Q->rear = 0;
}
void EnQueue(Queue* Q, BiTNode bt)
{
if ((Q->rear + 1) % MaxSize == Q->front) {
return;
}
Q->PArray[Q->rear] = bt;
Q->rear = (Q->rear + 1) % MaxSize;
return;
}
int IsQEmpty(Queue* Q)
{
int ret = 0;
if (Q->rear == Q->front) {
ret = 1;
}
return ret;
}
void DeQueue(Queue* Q, BiTNode* p)
{
if (Q->rear == Q->front) {
return;
}
*p = Q->PArray[Q->front];
Q->front = (Q->front + 1) % MaxSize;
return;
}
void Push(Stack* s, BiTNode p)
{
if (s->top == MaxSize - 1) {
printf("stack is full, push fail\n");
}
else {
s->PArray[++s->top] = p;
}
return;
}
int IsSEmpty(Stack* s)
{
int ret = 0;
if (s->top == -1) {
ret = 1;
}
return ret;
}
void Pop(Stack* s, BiTNode* p)
{
if (s->top == -1) {
printf("stack is empty, pop fail\n");
return;
}
*p = s->PArray[s->top--];
return;
}
void visit(BiTNode p)
{
printf("%d ", p->data);
}
void InvertLevel(BiTNode bt)
{
Stack s;
Queue Q;
BiTNode p = NULL;
if (bt != NULL) {
InitStack(&s);
InitQueue(&Q);
EnQueue(&Q, bt);
while (!IsQEmpty(&Q)) {
DeQueue(&Q, &p);
Push(&s, p);
if (p->lchild) {
EnQueue(&Q, p->lchild);
}
if (p->rchild) {
EnQueue(&Q, p->rchild);
}
} // while
while (!IsSEmpty(&s)) {
Pop(&s, &p);
visit(p);
}
} // if
}