本题代码如下
void postorder(tree* t)
{
struct treenode* stack[100];//初始化结构体数组
int top = -1;//让栈顶指向-1
treenode* p = *t;
while (p || top != -1)//p不为空,并且栈不为空
{
if (p)
{
top++;//p不为空,将p压入栈中
stack[top] = p;
p = p->lchild;//一直向左下遍历
}
else
{
p = stack[top];//p等于栈顶元素
if (p->rchild && p->rchild->tag == 0)//右孩子不为空且未被访问过
p = p->rchild;
else//否则弹出结点并访问
{
p = stack[top];
top--;
printf("%c", p->data);
p->tag = 1;//标记p被访问过
p = NULL;
}
}
}
}
完整测试代码
#include<stdio.h>
#include<stdlib.h>
typedef struct treenode
{
char data;
struct treenode* lchild, * rchild;
int tag;
}treenode,*tree;
void buildtree(tree *t)
{
char ch;
ch = getchar();
if (ch == '#')
*t = NULL;
else
{
*t = (treenode*)malloc(sizeof(treenode));
(*t)->data = ch;
(*t)->tag = 0;
(*t)->lchild = NULL;
(*t)->rchild = NULL;
buildtree(&(*t)->lchild);
buildtree(&(*t)->rchild);
}
}
void postorder(tree* t)
{
struct treenode* stack[100];//初始化结构体数组
int top = -1;//让栈顶指向-1
treenode* p = *t;
while (p || top != -1)//p不为空,并且栈不为空
{
if (p)
{
top++;//p不为空,将p压入栈中
stack[top] = p;
p = p->lchild;//一直向左下遍历
}
else
{
p = stack[top];//p等于栈顶元素
if (p->rchild && p->rchild->tag == 0)//右孩子不为空且未被访问过
p = p->rchild;
else//否则弹出结点并访问
{
p = stack[top];
top--;
printf("%c", p->data);
p->tag = 1;//标记p被访问过
p = NULL;
}
}
}
}
int main()
{
tree t;
buildtree(&t);
postorder(&t);
return 0;
}
用ABD##E##CF##G##
/* A
B C
D E F G
*/