前面的递归没有问题,后面的非递归的前序和中序也没有问题。
就是非递归的后序代码出错了。
请大神们帮忙看看哪地方错了?
#include <stdio.h>
#include <stdlib.h>
#define maxsize 100
typedef char datatype;
typedef struct node{
datatype data;
struct node *lchild,*rchild;
}Tnode,*BTree;
BTree CreateBinTree()
{
BTree t;
char ch;
ch=getchar();
if(ch=='#') t=NULL;
else
{
t=(Tnode*)malloc(sizeof(Tnode));
t->data=ch;
t->lchild=CreateBinTree();
t->rchild=CreateBinTree();
}
return t;
}
void PreOrder(BTree t)
{
if(t)
{
printf("%c",t->data);
PreOrder(t->lchild);
PreOrder(t->rchild);
}
}
void InOrder(BTree t)
{
if(t)
{
InOrder(t->lchild);
printf("%c",t->data);
InOrder(t->rchild);
}
}
void PostOrder(BTree t)
{
if(t)
{
PostOrder(t->lchild);
PostOrder(t->rchild);
printf("%c",t->data);
}
}
void PreOrder1(BTree t)
{
BTree s[maxsize];
int top=-1;
BTree p=t;
while(p||top!=-1)
{
while(p)
{
printf("%c",p->data);
top++;
s[top]=p;
p=p->lchild;
}
p=s[top];
top--;
p=p->rchild;
}
}
void InOrder1(BTree t)
{
BTree s[maxsize];
int top=-1;
BTree p=t;
while(p||top!=-1)
{
while(p)
{
top++;
s[top]=p;
p=p->lchild;
}
p=s[top];
printf("%c",p->data);
top--;
p=p->rchild;
}
}
void PostOrder1(BTree t)
{
BTree s1[maxsize];
BTree s2[maxsize];
int top=-1;
BTree p=t;
while(p||!s2)
{
while(p)
{
top++;
s1[top]=p;
s2[top]=p;
p=p->rchild;
}
p=s2[top];
top--;
p=p->lchild;
}
while(!s1)
{
p=s1[top];
printf("%c\n",p->data);
}
}
void main()
{
BTree t;
t=CreateBinTree();
PostOrder1(t);
}