二叉树的非递归遍历

来源:互联网 发布:单片机工程师月薪多少 编辑:程序博客网 时间:2024/06/03 20:28

/*二叉树的非递归遍历算法*/
/*注意指针的使用*/

#include<stdio.h>
#include<stdlib.h>

#define OK 1
#define ERROR 0
#define Start 2
#define Left 3
#define Right 4
#define MAXSIZE 50

typedef int Status;
typedef char ElemType;
/******************* 树 *******************/
typedef struct BiNode
{
 struct BiNode *lchild;
 struct BiNode *rchild;
 ElemType data;
 int flag;
}BiNode,*BiTree;
Status CreateTree(BiTree &T)
{
 ElemType c;
 scanf("%c",&c);
 if(c=='#') T=NULL;
 else
 {
  T=(BiNode*)malloc(sizeof(BiNode));
  T->data=c;
  CreateTree(T->lchild);
  CreateTree(T->rchild);
 }
 return OK;
}
Status PreOrder(BiTree T)
{
 if(T!=NULL)
 {
  if(T->data!='#') printf("%c ",T->data);
  PreOrder(T->lchild);
  PreOrder(T->rchild);
 }
 return OK;
}
Status InOrder(BiTree T)
{
 if(T!=NULL)
 {
  InOrder(T->lchild);
  if(T->data!='#') printf("%c ",T->data);
  InOrder(T->rchild);
 }
 return OK;
}
Status PoOrder(BiTree T)
{
 if(T!=NULL)
 {
  PoOrder(T->lchild);
  PoOrder(T->rchild);
  if(T->data!='#') printf("%c ",T->data);
 }
 return OK;
}
/***********************************************/
/*********************** 栈 **********************/
typedef BiTree SElemType;
typedef struct Stack
{
 SElemType *base;
 SElemType *top;
 int maxsize;
}Stack;
Status InitStack(Stack *S)
{
 S->base=(SElemType*)malloc(sizeof(SElemType)*MAXSIZE);
 S->top=S->base;
 S->maxsize=MAXSIZE;
 return OK;
}
bool StackEmpty(Stack *S)
{
 if(S->base == S->top) return 1;
 return 0;
}
Status Push(Stack *S,SElemType e)
{
 if(S->top - S->base >= S->maxsize)
 {
  printf("OVERFLOW!\n");
  return ERROR;
 }
 e->flag=Start;
 *S->top++=e;
 return OK;
}
Status Pop(Stack *S,SElemType *e)
{
 if(StackEmpty(S)) return ERROR;
 *e=*S->top--;
 return OK;
}
Status GetTop(Stack *S,SElemType *e)
{
 *e=*(S->top-1);
 return OK;
}
/*************************************************/
/******************************/
Status Visite(BiTree T,int kind)
{
 if(kind==1) printf("先序算法(非递归):\n");
 else if(kind==2) printf("中序算法(非递归):\n");
 else if(kind == 3) printf("后序算法(非递归):\n");
 Stack S;
 InitStack(&S);
 SElemType e;
 Push(&S,T);
 while(!StackEmpty(&S))
 {
  GetTop(&S,&e);
  if(e->flag==Start)
  {
   e->flag=Left;
   if(kind ==1) printf("%c ",e->data);
   if(e->lchild!=NULL)
   {
    Push(&S,e->lchild);
   }
  }
  else if(e->flag==Left)
  {
   if(kind==2) printf("%c ",e->data);
   e->flag=Right;
   if(e->rchild!=NULL)
   {
    Push(&S,e->rchild);
   }
  }
  else if(e->flag==Right)
  {
   if(kind==3) printf("%c ",e->data);
   Pop(&S,&e);
  }
 }
 printf("\n");
 return OK;
}
/******************************/
int main()
{
 BiTree T;
 CreateTree(T);
 PreOrder(T);
 printf("\n");
 InOrder(T);
 printf("\n");
 PoOrder(T);
 printf("\n");
 /***************/


 /***************/
 Visite(T,1);
 Visite(T,2);
 Visite(T,3);
 return 0;
}

0 0
原创粉丝点击