二叉树的前序/中序/后序/层序的非递归遍历算法

来源:互联网 发布:linux 剪切文件夹 编辑:程序博客网 时间:2024/04/29 05:21
    //前序遍历----非递归    void PreOrderBinaryTree_Nor()    {        if (NULL == _pRoot)            return;        cout << "PreOrderBinaryTree_Nor:" << endl;        stack<BinaryTreeNode<T>*> s;//使用栈        s.push(_pRoot);        while (!s.empty())        {            BinaryTreeNode<T>* pCur = s.top();            cout << pCur->_data << " ";            s.pop();            if (NULL != pCur->_pRightChild)                s.push(pCur->_pRightChild);            if (NULL != pCur->_pLeftChild)                s.push(pCur->_pLeftChild);        }        cout << endl;    }    //中序遍历----非递归    void InOrderBinaryTree_Nor()    {        if (NULL == _pRoot)            return;        cout << "InOrderBinaryTree_Nor:" << endl;        stack<BinaryTreeNode<T>*> s;//使用栈        BinaryTreeNode<T>* pCur = _pRoot;        while (pCur || !s.empty())        {            //找最左边的结点            while(pCur)            {                s.push(pCur);                pCur = pCur->_pLeftChild;            }            BinaryTreeNode<T>* pTop = s.top();            cout << pTop->_data << " ";            s.pop();            pCur = pTop->_pRightChild;        }        cout << endl;    }    //后序遍历----非递归    void PostOrderBinaryTree_Nor()    {        if (NULL == _pRoot)            return;        cout << "PostOrderBinaryTree_Nor:" << endl;        stack<BinaryTreeNode<T>*> s;//使用栈        BinaryTreeNode<T>* pCur = _pRoot;        BinaryTreeNode<T>* prev = NULL;//保存最近访问的结点        while (pCur || !s.empty())        {            while (pCur)            {                s.push(pCur);                pCur = pCur->_pLeftChild;            }            BinaryTreeNode<T>* pTop;            pTop = s.top();            if (NULL == pTop->_pRightChild || pTop->_pRightChild == prev)            {                cout << pTop->_data<<" ";                prev = pTop;                s.pop();            }            else            {                pCur = pTop->_pRightChild;            }        }        cout << endl;    }    //层序遍历    void LevelOrderBinaryTree()    {        if (NULL == _pRoot)            return;        cout << "LevelOrderBinaryTree:" << endl;        queue<BinaryTreeNode<T>*> q;//借助队列        q.push(_pRoot);        while (!q.empty())        {            BinaryTreeNode<T>* pCur = q.front();            cout << pCur->_data << " ";            if (NULL != pCur->_pLeftChild)                q.push(pCur->_pLeftChild);            if (NULL != pCur->_pRightChild)                q.push(pCur->_pRightChild);            q.pop();        }        cout << endl;    }
阅读全文
0 0
原创粉丝点击