这是递归的啊,我要的是非递归的
追答#include
#include
#include
#define Maxsize 20
#define Max 20
typedef struct BTree
{
char data;
struct BTree *Lchild, *Rchild;
}BTree;
typedef struct Stack
{
BTree *data[Maxsize];
int top;
}Stack;
void InitBTree(BTree *&B)
{
B=(BTree *)malloc(sizeof(BTree));
B=NULL;
printf("\n 目前已经创建一棵空二叉树\n");
}
void CreateBTree(BTree *&B) // 创建二叉树
{
char ch;
ch=getchar();
if(ch=='#')
{
B=NULL;
}
else
{
B=(BTree *)malloc(sizeof(BTree));
B->data=ch;
CreateBTree(B->Lchild);
CreateBTree(B->Rchild);
}
}
//先序遍历 递归算法
void Display(BTree *B)
{
if(B!=NULL)
{
printf("%c ", B->data);
Display(B->Lchild);
Display(B->Rchild);
}
}
void Preorder(BTree *B)
{
Stack *s;
s=(Stack *)malloc(sizeof(Stack));
s->top=0;
printf(" 先序遍历 非递归算法 输出二叉树所有结点内容:\n ");
while(B!=NULL||s->top>0)
{
if(B!=NULL)
{
printf("%c ", B->data);
s->data[s->top++]=B;
B=B->Lchild;
}
else
{
B=s->data[--s->top];
B=B->Rchild;
}
}
}
int main(void)
{
srand((unsigned)time(NULL));
BTree *B;
InitBTree(B);
printf("\n 开始初始化二叉树的结点内容:\n ");
CreateBTree(B);
printf("\n 二叉树的结点内容:\n ");
Display(B);
printf("\n");
Preorder(B);
printf("\n");
return 0;
}