最近正在学习二叉树,拿出来练习一下。
1、前序遍历:A B C D E F G H
void PastOrder(BtNode *ptr)
{
if (ptr != NULL)
{
PastOrder(ptr->leftchild);
PastOrder(ptr->rightchild);
printf("%c ", ptr->data);
}
}
void NicePerOrder(BtNode *ptr) //非递归
{
if (ptr == NULL) return;
stack st;
while (ptr != NULL || !empty(&st))//st != NULL)
{
while (ptr != NULL)
{
printf("%c ", ptr->data);
push(&st, ptr);
ptr = ptr->leftchild;
}
ptr = top(&st); pop(&st);
if (ptr->rightchild != NULL)
{
ptr = top(&st);
ptr = ptr->rightchild;
}
else
{
push(&st, ptr);
ptr = ptr->rightchild;
}
}
}
2、中序遍历:C B E D F A G H
void PastOrder(BtNode *ptr)
{
if (ptr != NULL)
{
PastOrder(ptr->leftchild);
PastOrder(ptr->rightchild);
printf("%c ", ptr->data);
}
}
void NiceInOrder(BtNode *ptr) //利用栈 碰到‘NULL’取出栈顶元素
{
if (ptr == NULL) return;
stack st;
while (ptr != NULL || !empty(&st))//st != NULL)
{
while (ptr != NULL)
{
push(&st, ptr);
ptr = ptr->leftchild;
}
ptr = top(&st); pop(&st);
printf("%c", ptr->data);
ptr = ptr->rightchild;
}
}
3、后序遍历:C E F D B H G A
{
if (ptr != NULL)
{
PastOrder(ptr->leftchild);
PastOrder(ptr->rightchild);
printf("%c ", ptr->data);
}
}
void NicePastOrder(BtNode *ptr)
{
if (ptr == NULL) return;
stack st;
BtNode *tag = NULL;
while (ptr != NULL || !empty(&st))//st != NULL)
{
while (ptr != NULL)
{
push(&st, ptr);
ptr = ptr->leftchild;
}
ptr = top(&st); pop(&st);
if (ptr->rightchild == NULL || ptr->rightchild == tag)//判断右结点为空或访问过
{
printf("%c ", ptr->data);
tag = ptr; //标记位上移
ptr = NULL; //ptr赋空 否则死循环
}
else
{
push(&st, ptr);
ptr = ptr->rightchild;
}
}
4、层次遍历
void LevelOrder(BtNode *ptr)
{
if (ptr == NULL) return; //根节点若为空,返回空
Queue qu;
Init_Queue(&qu);
Queue_push(&qu, ptr); //入队
while (!Queue_empty(&qu)) //当队列不为空时循环
{
BtNode *p=pop(&qu); //队头元素出对
printf("%c ", p->data);
if (ptr->leftchild)
Queue_push(&qu, p->leftchild); //左子树不空,则入队
if (ptr->rightchild)
Queue_push(&qu, p->rightchild); //右子树不空,则入队
}
}