6_39_二叉树增加两个域不用栈进行递推后序遍历树
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node
{
int data;
int mark;
struct node*lchild,*rchild,*parent;
}tnode,*tree;
tree creat()
{
int x;
tree t;
scanf("%d",&x);
if(x==0)t=NULL;
else
{
t=(tnode*)malloc(sizeof(tnode));
t->data=x;
t->mark=0;
t->parent=NULL;//初始化它没有双亲
t->lchild=creat();//左孩子的双亲是它
if(t->lchild)t->lchild->parent=t;
t->rchild=creat();//右孩子的双亲是它
if(t->rchild)t->rchild->parent=t;
}
return t;
}
void preorder(tree t)
{
if(t)
{
printf("tree:%d\t",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void postorder(tree t)
{
while(t)
{
if(t->mark==0){//标志为往左子树走
t->mark=1;//更改标记为往右
if(t->lchild)t=t->lchild;//如果左子树存在往左走
}
else if(t->mark==1){//往右走
t->mark=2;
if(t->rchild)t=t->rchild;
}
else if(t->mark==2){//访问本节点
printf("%d\n",t->data);
t->mark=0;//把它重置,以便下一次遍历
t=t->parent;//回到双亲
}
}
}
int main()
{
tree t=creat();
postorder(t);
postorder(t);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

浙公网安备 33010602011771号