#include <iostream> using namespace std; struct TreeNode { int m_nValue; TreeNode *m_pLeft; TreeNode *m_pRight; TreeNode(int _nNum, TreeNode *t1, TreeNode *t2) : m_nValue(_nNum), m_pLeft(t1), m_pRight(t2){} }; void ConvertTreeToDList(TreeNode *pNode, TreeNode * &pHead, TreeNode * &pTail) { if (!pNode) { pHead = NULL; pTail = NULL; return; } TreeNode *pLHead = NULL; TreeNode *pLTail = NULL; TreeNode *pRHead = NULL; TreeNode *pRTail = NULL; TreeNode *pCur = pNode; pHead = pCur; pTail = pCur; if (pNode->m_pLeft) { ConvertTreeToDList(pNode->m_pLeft, pLHead, pLTail); } if (pNode->m_pRight) { ConvertTreeToDList(pNode->m_pRight, pRHead, pRTail); } pCur->m_pLeft = pLTail; if (pLTail) { pLTail->m_pRight = pCur; } pCur->m_pRight = pRHead; if (pRHead) { pRHead->m_pLeft = pCur; } if (pLHead) { pHead = pLHead; } if (pRTail) { pTail = pRTail; } } void PrintDListTo(TreeNode *pHead) { while (pHead) { cout << pHead->m_nValue << ' '; pHead = pHead->m_pRight; } cout << endl; } void PrintDListFrom(TreeNode *pTail) { while (pTail) { cout << pTail->m_nValue << ' '; pTail = pTail->m_pLeft; } cout << endl; } int main() { TreeNode *t2 = new TreeNode(2, 0, 0); TreeNode *t7 = new TreeNode(7, 0, 0); TreeNode *t4 = new TreeNode(4, t2, t7); TreeNode *t9 = new TreeNode(9, 0, 0); TreeNode *t12 = new TreeNode(12, 0, 0); TreeNode *t10 = new TreeNode(10, t9, t12); TreeNode *t8 = new TreeNode(8, t4, t10); TreeNode *head, *tail; ConvertTreeToDList(t8, head, tail); PrintDListTo(head); PrintDListFrom(tail); return 0; }
二叉查找树转换为双向链表
最新推荐文章于 2021-03-01 19:42:10 发布