#include"stdio.h"
#include"malloc.h"
typedef struct Tree
{
char ch;
struct Tree *left;
struct Tree *right;
}Tree;
typedef struct Stack
{
Tree *data;
struct Stack *next;
}Stack;
void Push(Stack *s, Tree *p)
{
Stack *r;
r = (Stack *)malloc(sizeof(Stack));
r->data = p;
r->next = s->next;
s->next = r;
}
int IsEmpty(Stack *s)
{
if(!s->next)
return 1;
return 0;
}
Tree *Pop(Stack *s)
{
Stack *p;
p = s->next;
s->next = p->next;
return p->data;
}
Tree *getTop(Stack *s)
{
return s->next->data;
}
void InitStack(Stack **s)
{
(*s) = (Stack *)malloc(sizeof(Stack));
(*s)->next = NULL;
}
void createTree(Tree **T)
{
char ch;
ch = getchar();
if(ch=='.')
*T = NULL;
else
{
*T = (Tree *)malloc(sizeof(Tree));
(*T)->ch = ch;
createTree(&((*T)->left));
createTree(&((*T)->right));
}
}
void InitTree(Tree **T)
{
(*T) = (Tree *)malloc(sizeof(Tree));
(*T)->left = (*T)->right = NULL;
}
void preOrder(Tree *T)
{
if(T)
{
printf("%c ", T->ch);
preOrder(T->left);
preOrder(T->right);
}
}
void preOrder1(Tree *r)
{
Stack *s;
Tree *T;
T = r;
printf("%c ",T->ch);
InitStack(&s);
Push(s,T->right);
Push(s,T->left);
while(!IsEmpty(s))
{
r = Pop(s);
printf("%c ",r->ch);
if(r->right)
Push(s,r->right);
if(r->left)
Push(s,r->left);
}
printf("\n");
}
void InOrder(Tree *T)
{
if(T)
{
InOrder(T->left);
printf("%c ",T->ch);
InOrder(T->right);
}
}
void InOrder1(Tree *T)
{
Stack *s;
Tree *p,*r;
InitStack(&s);
p = T;
while(p || !IsEmpty(s))
{
if(p)
{
Push(s,p);
p = p->left;
}
else
{
r = Pop(s);
printf("%c ",r->ch);
p = r->right;
}
}
printf("\n");
}
void PostOrder(Tree *T)
{
if(T)
{
PostOrder(T->left);
PostOrder(T->right);
printf("%c ",T->ch);
}
}
void PostOrder1(Tree *T)
{
Stack *s;
Tree *r,*p;
InitStack(&s);
p = T;
r = NULL;
while(p || !IsEmpty(s))
{
if(p)
{
Push(s,p);
p = p->left;
}
else
{
p = getTop(s);
if(p->right && p->right != r)
{
p = p->right;
Push(s,p);
p = p->left;
}
else
{
p = Pop(s);
printf("%c ",p->ch);
r = p;
p = NULL;
}
}
}
printf("\n");
}
void levelOrder(Tree *T)
{
Tree *Queue[10],*r,*p;
int front,rear,i;
front = rear=0;
r = T;
Queue[rear++] = r;
while(front != rear)
{
p = Queue[front++];
printf("%c ",p->ch);
if(p->left!=NULL)
Queue[rear++] = p->left;
if(p->right!=NULL)
Queue[rear++] = p->right;
}
printf("\n");
}
void main()
{
Tree *T;
InitTree(&T);
createTree(&T);
printf("recursion preorder:");
preOrder(T);
printf("\n not recursion perorder:");
preOrder1(T);
printf("\n recursion InOrder:");
InOrder(T);
printf("\n not recursion InOrder:");
InOrder1(T);
printf("\n recursion postorder:");
PostOrder(T);
printf("\n not recursion postorder:");
PostOrder1(T);
printf("\n level order:");
levelOrder(T);
}
二叉树
最新推荐文章于 2022-05-01 12:47:37 发布