二叉树展开为单链表

#include <iostream>

using namespace std;

//二叉树结构体
struct BinaryTreeNode
{
    explicit BinaryTreeNode(int value)
    :m_nValue(value)
    ,m_pLeft(nullptr)
    ,m_pRight(nullptr)
    {}
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
};

void flatten(BinaryTreeNode* pRoot, BinaryTreeNode*& pLast)
{
    if(pRoot == nullptr) return;
    if(pRoot->m_pLeft == nullptr && pRoot->m_pRight == nullptr)
    {
        pLast = pRoot;
        return;
    }
    BinaryTreeNode* pLeft = pRoot->m_pLeft, *pRight = pRoot->m_pRight;
      
     //中
    pRoot->m_pLeft = nullptr;
    pRoot->m_pRight = pLeft;

      //左
    if(pLeft)
    {
        flatten(pLeft, pLast);
    }

       //右
    if(pRight)
    {
        if(pLast)
        {
            pLast->m_pRight = pRight;   
        }
        pLast = pRight;
        flatten(pRight, pLast);
    }
}

void pre_order(BinaryTreeNode* pRoot)
{
    if(pRoot == nullptr) return;
    cout << pRoot->m_nValue << " ";
    pre_order(pRoot->m_pLeft);
    pre_order(pRoot->m_pRight);
}

int main()
{
    BinaryTreeNode* pRoot = new BinaryTreeNode(1);
    pRoot->m_pLeft = new BinaryTreeNode(2);
    pRoot->m_pRight = new BinaryTreeNode(5);
    pRoot->m_pRight->m_pRight = new BinaryTreeNode(7);
    pRoot->m_pRight->m_pLeft = new BinaryTreeNode(6);
    pRoot->m_pLeft->m_pLeft = new BinaryTreeNode(3);
    pRoot->m_pLeft->m_pRight = new BinaryTreeNode(4);

    pre_order(pRoot);
    cout << endl;

    BinaryTreeNode* pNode = nullptr;
    flatten(pRoot, pNode);

    pre_order(pRoot);
    cout << endl;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容