将搜索二叉树转化为双向链表

用二叉树的_pLeft表示_prev,用二叉树的_pRight表示_next。
用中序遍历的方式遍历整棵二叉树。

Node* BothwayList()
    {
        if(!_pRoot)
            return NULL;
        stack<Node*> s;
        s.push(_pRoot);
        Node* pCur = NULL;
        Node* pPre = _GetLeftNode();
        Node* pHead = pPre;
        size_t flag = 0;
        while(!s.empty())
        {
            pCur = s.top();
            while(pCur->_pLeft)
            {
                s.push(pCur->_pLeft);
                pCur = s.top();
            }
            if(flag == 0)
                flag = 1;
            else
            {
                pPre->_pRight = pCur;
                pCur->_pLeft = pPre;
                pPre = pCur;
            }
            s.pop();
            while(!pCur->_pRight && !s.empty())
            {
                pCur = s.top();
                pPre->_pRight = pCur;
                pCur->_pLeft = pPre;
                pPre = pCur;
                s.pop();
            }
            if(pCur->_pRight)
                s.push(pCur->_pRight);
        }
        return pHead;
    }

因为第一个最左结点pPre = pCur,所以不需要修改_pLeft和_pRight的值,所以用flag记录第一次的最左结点。

你可能感兴趣的:(二叉树,链表,搜索,刷题)