void inorder_non_rec(btree tree)
{
ptrtonode temp = tree;//ptrtonode为指向节点的指针类型
struct stack s;
stack_create(&s);//创建一个新堆栈
while (temp)
{
PushLeftTree:
for (;temp;temp = temp->left)
push(&s,temp);//左子树各节点入栈
Visit:
if ((temp = pop(&s)) != NULL)
{
visit(temp);
}
else return;
if (temp->right)
{
temp = temp->right;
goto PushLeftTree;
}
else
goto Visit;
}
stack_free(&s);
}
二叉树遍历的非递归算法,借助堆栈进行遍历(以中序遍历为例):
1、将根节点入栈
2、判断根节点的左子树是否为空,若非空,继续入栈,知道某个节点的左子树为空
3、若为空,则弹出栈顶元素,访问后判断其右子树,若非空,则重复1到3
4、若为空,则重复3
新人出来乍到,语言写的不太清楚,见谅啊。