- 主要思想:
每遇到一个结点,先访问该结点,并把该结点的非空右子结点推入栈中,然后周游其左子树;
左子树周游不下去时,从栈顶弹出待访问的结点,继续周游。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 20
typedef char TElemType;
typedef int Status;
typedef struct BiTNode //二叉树的链式存储结构
{
TElemType data;
struct BiTNode * lchild;
struct BiTNode * rchild;
}BiTnode,*BiTree;
typedef BiTree SElemType;
typedef struct //顺序栈的储存结构
{
SElemType data[MAXSIZE];
int top; //用于栈顶指针
}Sqstack;
//顺序栈的初始化
Status InitSqstack(Sqstack * S)
{
S->top=-1;
return OK;
}
//出栈操作
Status Pop(Sqstack * S,SElemType * e)
{
if(S->top==-1) //栈底
{
return ERROR;
}
*e=S->data[S->top];
S->top--;
return OK;
}
//进栈操作
Status Push(Sqstack * S,SElemType e)
{
if(S->top==MAXSIZE-1) //栈满
{
return ERROR;
}
S->top++; //栈顶指针增加1
S->data[S->top]=e;
return OK;
}
void CreateBiTree(BiTree * T) //二叉树的建立
{
TElemType ch;
scanf("%c",&ch);
if(ch=='#')
{
*T=NULL;
}
else
{
(*T)=(BiTree)malloc(sizeof(BiTNode));
}
if(!(*T))
{
return ;
}
else
{
(*T)->data=ch;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
//非递归前序周游二叉树
void PerOrderWithoutRecursion(BiTree * T,Sqstack * S)
{
if(!(*T))
{
printf("空树!\n");
return ;
}
while((*T)!=NULL || S->top!=-1)
{
while((*T))
{
if((*T)->rchild!=NULL)
{
Push(S,(*T)->rchild);
}
printf("%c ",(*T)->data);
(*T)=(*T)->lchild;
}
Pop(S,&(*T));
}
printf("\n");
}
int main()
{
BiTree root;
Sqstack S;
InitSqstack(&S);
printf("Enter the data :\n");
CreateBiTree(&root);
printf("PerOrderWithoutRecursion the data:\n");
PerOrderWithoutRecursion(&root,&S);
return 0;
}
“`