二叉树的建立与七种遍历方法
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef struct node
{
char data;
struct node *left, *right;
}*Node;
node *input()
{
node *p;
char c;
scanf_s("%c", &c);
if (c == '#')
{
p = NULL;
}
else
{
p = (struct node *)malloc(sizeof(node));
p->data = c;
p->left = input();
p->right = input();
}
return p;
}
typedef struct
{
Node data[MAXSIZE];
int rear, front;
}SeQueue;
SeQueue *init_Queue()
{
SeQueue *sq;
sq = (SeQueue*)malloc(sizeof(SeQueue));
sq->front = sq->rear = -1;
return sq;
}
int Empty_Queue(SeQueue *sq)
{
if (sq->front == sq->rear)
return 1;
else
return 0;
}
void In_Queue(SeQueue *sq, Node x)
{
if (sq->rear == MAXSIZE - 1)
{
printf("\n顺序队列是满的!");
exit(1);
}
sq->rear++;
sq->data[sq->rear] = x;
}
void Out_Queue(SeQueue *sq, Node x)
{
if (Empty_Queue(sq))
{
printf("\n顺序队列是空的!不能做删除操作!");
exit(1);
}
sq->front++;
x = sq->data[sq->front];
}
void LevelOrder(Node T)
{
Node p = T;
SeQueue *sq = init_Queue();
In_Queue(sq, p);
while (!Empty_Queue(sq))
{
p = sq->data[sq->front + 1];
printf("%c ", p->data);
Out_Queue(sq, p);
if (p->left != NULL)
{
In_Queue(sq, p->left);
}
if (p->right != NULL)
{
In_Queue(sq, p->right);
}
}
}
void PreOrder(Node t)
{
Node stack[MAXSIZE];
int top = -1;
while (t || top != -1)
{
while (t)
{
printf("%c ", t->data);
top++;
stack[top] = t;
t = t->left;
}
if (top > -1)
{
t = stack[top];
top--;
t = t->right;
}
}
}
void preorder(Node t)
{
if (t)
{
printf("%c ", t->data);
preorder(t->left);
preorder(t->right);
}
}
void InOrder(Node t)
{
Node stack[MAXSIZE];
int top = -1;
while (t || top != -1)
{
while (t)
{
top++;
stack[top] = t;
t = t->left;
}
if (top > -1)
{
t = stack[top];
top--;
printf("%c ", t->data);
t = t->right;
}
}
}
void inorder(Node t)
{
if (t)
{
inorder(t->left);
printf("%c ", t->data);
inorder(t->right);
}
}
void PostOrder(Node t)
{
Node stack[MAXSIZE];
int stack1[MAXSIZE];
int top = -1;
while (t || top != -1)
{
while (t)
{
top++;
stack[top] = t;
stack1[top] = 0;
t = t->left;
}
while (top > -1 && stack1[top] == 1)
{
t = stack[top];
printf("%c ", t->data);
top--;
}
if (top > -1)
{
t = stack[top];
stack1[top] = 1;
t = t->right;
}
else
{
t = NULL;
}
}
}
void postorder(Node t)
{
if (t)
{
postorder(t->left);
postorder(t->right);
printf("%c ", t->data);
}
}
int main()
{
Node p;
p = (struct node *)malloc(sizeof(node));
p = input();
printf("层次遍历:");
LevelOrder(p);
printf("\n");
printf("非递归前序遍历:");
PreOrder(p);
printf("\n");
printf("递归前序遍历:");
preorder(p);
printf("\n");
printf("非递归中序遍历:");
InOrder(p);
printf("\n");
printf("递归中序遍历:");
inorder(p);
printf("\n");
printf("非递归后序遍历:");
PostOrder(p);
printf("\n");
printf("递归后序遍历:");
postorder(p);
printf("\n");
system("pause");
return 0;
}