#include <stdio.h>
#include <stdlib.h>
typedef struct node{
char data;
struct node *llink;
struct node *rlink;
}NODE;
NODE*build()//
{
NODE *tree;
char c;
scanf("%c",&c);
if(c=='#') tree = NULL;
else
{
tree=(NODE*)malloc(sizeof(NODE));
tree->data=c;
tree->llink=build();
tree->rlink=build();
}
return tree;
}
void houxu(NODE*tree)
{
NODE*pt=tree;
int tt[100],top=-1;
NODE*s[100];
do
{
while(pt!=NULL)
{
s[++top]=pt;
tt[top]=0;
pt=pt->llink;
}
if(top>=0)
{
if(!tt[top])
{
pt=s[top];
tt[top]=1;
pt=pt->rlink;
}
else printf("%c",s[top--]->data);
}
}while((pt!=NULL)||(top!=-1));
}
int main()
{
printf("请输入树的结点:\n");
NODE*tree=(NODE*)malloc(sizeof(NODE));
tree=build();
printf("后序遍历的结果是:\n");
houxu(tree);
printf("\n");
return 0;
}
/*测试数据
abd##e##cf###
输出:debfca
*/
#include <stdlib.h>
typedef struct node{
char data;
struct node *llink;
struct node *rlink;
}NODE;
NODE*build()//
{
NODE *tree;
char c;
scanf("%c",&c);
if(c=='#') tree = NULL;
else
{
tree=(NODE*)malloc(sizeof(NODE));
tree->data=c;
tree->llink=build();
tree->rlink=build();
}
return tree;
}
void houxu(NODE*tree)
{
NODE*pt=tree;
int tt[100],top=-1;
NODE*s[100];
do
{
while(pt!=NULL)
{
s[++top]=pt;
tt[top]=0;
pt=pt->llink;
}
if(top>=0)
{
if(!tt[top])
{
pt=s[top];
tt[top]=1;
pt=pt->rlink;
}
else printf("%c",s[top--]->data);
}
}while((pt!=NULL)||(top!=-1));
}
int main()
{
printf("请输入树的结点:\n");
NODE*tree=(NODE*)malloc(sizeof(NODE));
tree=build();
printf("后序遍历的结果是:\n");
houxu(tree);
printf("\n");
return 0;
}
/*测试数据
abd##e##cf###
输出:debfca
*/
本文介绍了一个使用C语言实现的二叉树后序遍历算法。通过递归方式构建二叉树,并采用非递归的方法实现了后序遍历。用户可以输入二叉树节点来构建树结构,然后程序会输出后序遍历的结果。
3793

被折叠的 条评论
为什么被折叠?



