二叉树的先中后序遍历的非递归算法都和栈有关,栈的相关操作请点此查看。
①先序遍历
思路一:先将根结点进栈,当栈不为空时,出栈并访问,然后依次将右左结点进栈(栈先进后出,所以先进栈右结点)。
顺序栈类型:
typedef struct
{
Btnode *data[MaxSize];
int top;
}Sqstack;
思路一的实现:
void PreOrder(Btnode *b)
{
Btnode *p;
SqStack st;
InitStack(st);
if (b != NULL)
{
Push(st, b);
while (!StackEmpty(st))
{
Pop(st, p);
cout << p->data;
if (p->right != NULL)
Push(st, p->right);
if (p->left != NULL)
Push(st, p->left);
}
cout << '\n';
}
DestroyStack(st);
}
思路二:和先序遍历的定义相似:先访问根结点,再遍历左子树,最后遍历右子树。
实现:
void PreOrder(Btnode *b)
{
Btnode *p;
SqStack *st;
InitStack(st);
p = b;
while (!StackEmpty(st) || p != NULL)
{
while (p != NULL)
{
cout << p->data;
Push(st, p);
p = p->left;
}
if (!StackEmpty(st))
{
Pop(st, p);
p = p->right;
}
}
cout << '\n';
DestroyStack(st);
}
②中序遍历
中序遍历的非递归算法和先序遍历的非递归算法的思路二相似,只有很微小的改变。
void InOrder(Btnode *b)
{
Btnode *p;
SqStack *st;
InitStack(st);
p = b;
while (!StackEmpty(st) || p != NULL)
{
while (p != NULL)
{
Push(st, p);
p = p->left;
}
if (!StackEmpty(st))
{
Pop(st, p);
cout << p->data;
p = p->right;
}
}
cout << '\n';
DestroyStack(st);
}
③后序遍历
先将根结点和左下结点依次进栈,遍历栈顶元素的右子树,只有当它的右子树也遍历完才能访问。
void PostOrder(Btnode *b)
{
int flag;
Btnode *p, *r;
SqStack *st;
InitStack(st);
p = b;
do
{
while (p != NULL)
{
Push(st, p);
p = p->left;
}
r = NULL;
flag = 1;
while (!StackEmpty(st) && flag == 1)
{
GetTop(st, p);
if (p->right == r)
{
cout << p->data;
Pop(st, p);
r = p;
}
else
{
p = p->right;
flag = 0;
}
}
}while (!StackEmpty(st));
cout << '\n';
DestroyStack(st);
}
---代码参考自《数据结构教程》