非递归遍历二叉树利用栈的先进先出特点完成实现

前序比较好理解先压根入栈,在while里面访问根,根出栈,再压入右子树,左子树,这样的遍历二叉树就是前序遍历了。

void PrevOrdr_NonR()

{

    stack*> s;

    s.push(_root);

    while(!s.empty())

    {

       BinaryTreeNode* top = s.top();

       s.pop();

       cout<_data<<" ";

       if(top->_right)

           s.push(top->_right);

       if(top->_left)

           s.push(top->_left); 

    }

    cout<

}

中序的遍历顺序是左子树、根节点、右子树。

void InOreder_NonR()

{

    stack*> s;

    BinaryTreeNode* cur = _root;

    while(cur || !s.empty())

    {

        while(cur)//把左路径的节点全部压入栈

        {

            s.push(cur);

            cur = cur->_left;

        }

        if(!s.empty())

        {

            BinaryTreeNode* top = s.top();

            s.pop();

            cout<_data<<" ";

            cur = cur->_right;//把cur指向最后一个左节点的右节点

        }

    }

    cout<

}

后序遍历是左子树、右子树、根节点。

void PostOrder_NonR()

{

    stack*> s;

    BinaryTreeNode* cur = _root;

    BinaryTreeNode* prevVisited = NULL;

    while(cur || s.empty())

    {

        while(cur)//左路径的节点入栈

        {

            s.push(cur);

            cur = cur->_left;

        }

        BinaryTreeNode* top = s.top();

        if(top->_right == NULL || top->right == preVisited)

        //当子树遍历之后回退到上一个没有遍历的子树

        {

            cout<_data<<" ";

            preVisited = tmp;

            s.pop();

        }

        else

        {

            cur = cur->left;//把cur指向右子树继续寻找左节点

        }

    }

}