#include <iostream>
using namespace std;
//二叉樹結(jié)構(gòu)體
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;
}
二叉樹展開為單鏈表
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。