一、递归遍历:
<1> 前序遍历: 若二叉树为空,则空操作返回,否则先访问根结点,然后前序遍历左子树, 再前序遍历右子树 ;
void preorder(btnode *ptr)
{
if (ptr!=NULL)
{
printf("%d ",ptr->data);
preorder(ptr->leftchild);
preorder(ptr->rightchild);
}
}
<2>中序遍历:若树为空,则空操作返回,否则从根结点开始,先遍历根结点的左子树,然后是访问根结点,最后中序遍历右子树 ;
void inorder(btnode *ptr)
{
if(ptr != NULL)
{
inorder(ptr->leftchild);
printf("%c ",ptr->data);
inorder(ptr->rightchild);
}
}
<3>后序遍历:
若树为空,则空操作返回,否则从左到右先叶子后结点的方式遍历访问左子树和右子树,最后是访问根结点 ;
void pastorder(btnode *ptr)
{
if(ptr != NULL)
{
pastorder(ptr->leftchild);
pastorder(ptr->rightchild);
printf("%c ",ptr->data);
}
}
二、非递归遍历(利用栈实现)
<1>前序遍历:
void NicePerOrder(BtNode *ptr)
{
if(ptr == NULL)
{
return ;
}
Stack st; //栈初始化
Init_Stack(&st);
push(&st,ptr); //根结点入栈
while(!empty(&st)) //遍历结束 :栈空
{
ptr = top(&st);
pop(&st);
printf("%c ",ptr->data);
if(ptr->rightchild != NULL)
{
push(&st,ptr->rightchild);
}
if(ptr->leftchild != NULL)
{
push(&st,ptr->leftchild);
}
}
}
<2>中序遍历:
void NiceInOrder(BtNode *ptr)
{
if(ptr == NULL) return ;
Stack st; // BtNode *;
Init_Stack(&st);
while(ptr != NULL || !empty(&st))
{
while(ptr != NULL)
{
push(&st,ptr);
ptr = ptr->leftchild;
}
ptr = top(&st); pop(&st);
printf("%c ",ptr->data);
ptr = ptr->rightchild;
}
}
<3>后序遍历:
void NicePastOrder(BtNode *ptr)
{
if(ptr == NULL)
{
return ;
}
Stack st;
Init_Stack(&st);
BtNode *tag = NULL;
while(ptr != NULL || !empty(&st))
{
while(ptr != NULL)
{
push(&st,ptr);
ptr = ptr->leftchild;
}
ptr = top(&st);
pop(&st);
if(ptr->rightchild == NULL || ptr->rightchild == tag) //tag 父节点
{
printf("%c ",ptr->data);
tag = ptr;
ptr = NULL;
}
else
{
push(&st,ptr);
ptr = ptr->rightchild;
}
}
}