先序遍历:
struct node{
int data;
node *lchild,*rchild;
};
void PreOrder(node *T)
{
node *p = T;
Stack s;
while(p || isempty(s))
{
while(p)
{
push(p);
printf("%d",p->data);
p = p->lchild;
}
if(!isempty(s))
{
p = pop(s);
p = p->rchild;
}
}
}
中序遍历:
struct node{
int data;
node *lchild,*rchild;
};
void InOrder(node *T)
{
node *p = T;
Stack s;
while(p || !isempty(s))
{
while(p)
{
push(p);
p = p->lchild;
}
if(isempty(s))
{
p = pop(s);
printf("%d",p->data);
p = p->rchild;
}
}
}
后序遍历:
struct node{
int data;
node *lchild,*rchild;
int flag = 0; //表示是否被访问过
};
void PostOrder(node *T)
{
node *p = T;
Stack s;
while(p || isempty(s))
{
while(p)
{
push(p);
p = p->lchild;
}
if(!isempty(s))
{
p = getTop(s);
if(p->rchild && p->rchild->flag ==0) //如果有右孩子,并且没有被访问过
{
p = p->rchild;
}else
{
p = pop(s);
printf("%d",p->data);
p->flag = 1;
p = NULL; //每次出栈一个结点,相当于遍历完以该节点为根的子树,将p置NULL
}
}
}
}