【非递归前中后序遍历二叉树】
有关二叉树的建立及基本操作在上一篇,戳链接二叉树的基本操作
【非递归·前序】
//非递归 前序遍历
void BTreePrevOrderNonR(BTNode* root)
{
BTNode* cur = root;
BTNode* top = NULL;
stack S;
StackInit(&S);
while (cur || StackEmpty(&S) != 0)
{
while (cur)
{
printf("%d", cur->_data);//访问结点
StackPush(&S, cur);
cur = cur->_left;//左子树
}
top = StackTop(&S);
StackPop(&S);
cur = top->_right;//右子树
}
}
【非递归·中序】
//非递归 中序遍历
void BTreeInOrderNonR(BTNode* root)
{
BTNode* cur = root;
BTNode* top = NULL;
stack S;
StackInit(&S);
while (cur || StackEmpty(&S) != 0)
{
while (cur)
{
StackPush(&S, cur);
cur = cur->_left;//走到最左结点
}
top = StackTop(&S);
printf("%d", top->_data);
StackPop(&S);
cur = top->_right;
}
}
【非递归·后序】
//非递归 后序遍历
void BTreePostOrderNonR(BTNode* root)
{
BTNode* cur = root, *top = NULL, *prev = NULL;
Stack S;
StackInit(&S);
while (cur || StackEmpty(&S) != 0)
{
while (cur)
{
StackPush(&S, cur);
cur = cur->_left;
}
top = StackTop(&S);
if (top->_right == NULL || top->_right == prev)//判断右子树有没有访问
{
printf("%d", top->_data);
prev = top;
StackPop(&S);
}
else//右子树没有被访问
{
cur = top->_right;
}
}
}
如果有不对的地方,可以评论告诉我,望指导!