先序遍历、中序遍历、后续遍历的非递归遍历,代码已测试

struct BinaryTreeNode 
{
    int                    m_nValue; 
    BinaryTreeNode*        m_pLeft;  
    BinaryTreeNode*        m_pRight; 
};

 struct StackNode
{
    BinaryTreeNode* treeNode;
    bool isRightHasVisited;// 用于标记右子树是否访问过
};


//先序遍历非递归算法
void PreorderUnrec(BinaryTreeNode* root)
{
    stack<BinaryTreeNode*> s;
    BinaryTreeNode* p=root;
    while(NULL!=p||!s.empty())
    {
        while(NULL!=p)
        {
            printf("%d  ",p->m_nValue);
            s.push(p);
            p=p->m_pLeft;
        }
        if(!s.empty())
        {
            p=s.top();
            s.pop();
            p=p->m_pRight;
        }
    }
}

//中序遍历非递归算法
void InorderUnrec(BinaryTreeNode* root)
{
    stack<BinaryTreeNode*> s;
    BinaryTreeNode* p=root;
    while(NULL!=p||!s.empty())
    {
        while(NULL!=p)
        {
            s.push(p);
            p=p->m_pLeft;
        }
        if(!s.empty())
        {
            p=s.top();
            s.pop();
            printf("%d  ",p->m_nValue);
            p=p->m_pRight;
        }
    }
}
//后序遍历非递归算法
void PostOrderUnrec(BinaryTreeNode* root)
{
    stack<StackNode> s;
    StackNode stackNode;
    BinaryTreeNode* p=root;
    do
    {
        while(p!=NULL)
        {
            stackNode.treeNode=p;
            stackNode.isRightHasVisited=false;
            s.push(stackNode);
            p=p->m_pLeft;
        }
        while(!s.empty()&&s.top().isRightHasVisited==true)
        {
            stackNode=s.top();
            s.pop();
            p=stackNode.treeNode;
            printf("%d  ",p->m_nValue);
        }
        if(!s.empty())
        {
            s.top().isRightHasVisited=true;
            p=s.top().treeNode->m_pRight;
        }
    }while(!s.empty());
}

 

posted @ 2013-07-30 12:56  芒刺  阅读(264)  评论(0编辑  收藏  举报