Preorder traversal operation is as follows:
1) access to the root node;
2) preorder left subtree;
3) preorder right subtree;
Corresponding to the following recursive algorithm:
void PreOrder(Bitree T) {
if (T != NULL) {
visit(T);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
Corresponding to the non-recursive algorithm is as follows:
void PreOrder2(Bitree T) {
//借助栈实现
InitStack(S); Bitree p = T; //初始化栈,p是遍历指针
while (p || !IsEmpty(S)) {
if (p) {
Push(S, p);
visit(p); //访问根节点
p = p->lchild; //遍历左子树
}
else {
Pop(S, p);
p = p->rchild; //遍历左子树
}
}
}