二叉树的后序非递归遍历
头文件
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<math.h>
#include<string.h>
typedef char elemtype;
typedef struct bintreenode
{
elemtype data;
struct bintreenode *leftchild;
struct bintreenode *rightchild;
}bintreenode,*binlink;
typedef struct stknode
{
int tag;
binlink post;
}stknode;
#define Elemtype stknode
typedef struct snode {
Elemtype data;
struct snode* next;
}snode, * linkstack;
void initstack(linkstack& s);
void pushstack(linkstack& s, Elemtype x);
void popstack(linkstack& s, Elemtype& x);
int isempty(linkstack &s);
void initstack(linkstack& s)
{
s = (linkstack)malloc(sizeof(snode));
s->next = NULL;
}
void pushstack(linkstack& s, Elemtype x)
{
linkstack p = (linkstack)malloc(sizeof(snode));
p->data = x;
p->next = s;
s = p;
}
void popstack(linkstack& s, Elemtype& x)
{
linkstack p = s;
x = p->data;
if(s->next==NULL)
{
s->next = NULL;
}
else {
s = s->next;
}
free(p);
}
int isempty(linkstack &s)
{
if(s->next==NULL)
{
return 1;
}
else
{
return 0;
}
}
主函数
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#include"stack.h"
typedef struct bintree
{
binlink root;
elemtype refvalue;
}bintree;
void initbintree(bintree *bt,elemtype ref);
void createbintree(bintree *bt,elemtype *str);
void createbintree(bintree *bt,binlink &t,elemtype *&str);
void postorder(bintree *bt);
void postorder(binlink t);
void main()
{
elemtype *str="ABC##DE##F##G#H##";
bintree mytree;
initbintree(&mytree,'#');
createbintree(&mytree,str);
printf("非递归遍历");
postorder(&mytree);printf("\n");
}
void initbintree(bintree *bt,elemtype ref)
{
bt->root=NULL;
bt->refvalue=ref;
}
void createbintree(bintree *bt,elemtype *str)
{
createbintree(bt,bt->root,str);
}
void createbintree(bintree *bt,binlink &t,elemtype *&str)
{
if(*str==bt->refvalue)
{
t=NULL;
}
else
{
t=(binlink)malloc(sizeof(bintreenode));
assert(t!=NULL);
t->data=*str;
createbintree(bt,t->leftchild,++str);
createbintree(bt,t->rightchild,++str);
}
}
void postorder(bintree *bt)
{
postorder(bt->root);
}
void postorder(binlink t)
{
if(t!=NULL)
{
linkstack st;
initstack(st);
stknode sn;
binlink bs;
do{
while(t!=NULL)
{
sn.post=t;
sn.tag=0;
pushstack(st,sn);
t=t->leftchild;
}
bool flag=true;
while(flag&&!isempty(st))
{
popstack(st,sn);
bs=sn.post;
switch(sn.tag)
{
case 0:
sn.tag=1;
pushstack(st,sn);
flag=false;
t=bs->rightchild;
break;
case 1:
printf("%c",bs->data);
break;
}
}
}while(!isempty(st));
}
}