Non-recursive binary tree traversal sequence recursive

Inorder traversal operation is as follows:
1) preorder left subtree;
2) access to the root node;
3) in order to traverse the right subtree;


Corresponding to the following recursive algorithm:

void InOrder(Bitree T) {
    if (T != NULL) {
        InOrder(T->lchild);
        visit(T);
        InOrder(T->rchild);
    }
}

Corresponding to the non-recursive algorithm is as follows:

void InOrder2(Bitree T) {
    //借助栈实现
    InitStack(S); Bitree p = T;   //初始化栈,p是遍历指针
    while (p || !IsEmpty(S)) {
        if (p) {
            Push(S, p);
            p = p->lchild;     //中序遍历左子树
        }
        else {
            Pop(S, p);
            visit(p);             //访问根节点
            p = p->rchild;   //中序遍历右子树
        }
    }
}

Guess you like

Origin www.cnblogs.com/brainstorm-yc/p/11762140.html