二叉树的创建和递归与非递归遍历

二叉树的创建

//index要给引用!!!
    void _Create(Node *&pRoot,T *arr,T invalid,size_t sz,size_t &index)
    {
        if (arr[index] != invalid&&index < sz)
        {
            pRoot = new Node(arr[index]);
            _Create(pRoot->_pLeft, arr, invalid, sz, ++index);
            _Create(pRoot->_pRight, arr, invalid, sz, ++index);
        }
    }

二叉树的递归遍历

void _Order(Node *pRoot)
    {
        if (NULL != pRoot)
        {
            cout << pRoot->_data << " ";//前序
            _Order(pRoot->_pLeft);
            //cout << pRoot->_data << " ";//中序
            _Order(pRoot->_pRight);
            //cout << pRoot->_data << " ";//后序
        }
    }

二叉树的非递归遍历

  1. 前序遍历
void _PreOrder_Nor(Node *pRoot)
    {
        stack<Node *> st;
        //要记得加上pRoot存在的情况下,防止右单支存在的情况同时防止空树
        while (pRoot||!st.empty())
        {
            while (pRoot)
            {
                cout << pRoot->_data<< " ";
                st.push(pRoot);
                pRoot = pRoot->_pLeft;
            }
            Node *pTop = st.top();
            st.pop();
            pRoot = pTop->_pRight;
        }
    }
  1. 中序遍历
void _InOrder_Nor(Node *pRoot)
    {
        stack<Node *> st;
        while (pRoot||!st.empty())
        {
            while (pRoot)
            {
                st.push(pRoot); 
                pRoot = pRoot->_pLeft;  
            }
            Node *pTop = st.top();
            cout << pTop->_data << " ";
            st.pop();
            pRoot = pTop->_pRight;
        }
    }
  1. 后续遍历:
void _PostOrder(Node *pRoot)
    {
        stack<Node *> st;
        //给个flag,标记节点是否被访问过
        Node *pPreNode=NULL;
        while (pRoot || !st.empty())
        {
            while (pRoot)
            {
                st.push(pRoot);
                pRoot = pRoot->_pLeft;
            }
            Node *pTop = st.top();
            if (NULL == pTop->_pRight||pPreNode==pTop->_pRight)
            {
                cout << pTop->_data<<" ";
                pPreNode = pTop;
                st.pop();
            }
            //如果右边不为空或者右边没有被访问过,则向右边拐
            else
                pRoot = pTop->_pRight;

        }
    }

 4.层序遍历:

void _LevelOrder(Node *pRoot)
    {
        if (NULL == pRoot)
            return;
        queue<Node *> q;
        q.push(pRoot);
        while (!q.empty())
        {
            Node *pTop = q.front();
            cout << pTop->_data << " ";
            if (pTop->_pLeft)
                q.push(pTop->_pLeft);
            if (pTop->_pRight)
                q.push(pTop->_pRight);
            q.pop();
        }
    }
    原文作者:满二叉树
    原文地址: https://blog.csdn.net/gjggj/article/details/72457762
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞