#include "stdafx.h" #include <iostream> using namespace std; struct BinaryTreeNode { int m_nValue; BinaryTreeNode *m_pLeft; BinaryTreeNode *m_pRight; }; void Convert(BinaryTreeNode *pRoot, BinaryTreeNode *&pLastInList) { if (pRoot == NULL) { return; } BinaryTreeNode *pCurrentNode = pRoot; if (pCurrentNode->m_pLeft != NULL) { Convert(pCurrentNode->m_pLeft, pLastInList); } pCurrentNode->m_pLeft = pLastInList; if (pLastInList != NULL) { pLastInList->m_pRight = pCurrentNode; } pLastInList = pCurrentNode; if (pCurrentNode->m_pRight != NULL) { Convert(pCurrentNode->m_pRight, pLastInList); } } BinaryTreeNode *ConvertBSTToDoubleList(BinaryTreeNode *pRoot) { if (pRoot == NULL) { return NULL; } BinaryTreeNode *pLastInList = NULL;//指向排好序的雙向鏈表的最後一個結點 Convert(pRoot, pLastInList); while (pLastInList->m_pLeft != NULL)//返回到頭結點 { pLastInList = pLastInList->m_pLeft; } return pLastInList; } //以先序的方式構建二叉樹,輸入-1表示結點為空 void CreateBinaryTree(BinaryTreeNode *&pRoot) { int nNodeValue = 0; cin >> nNodeValue; if (-1 == nNodeValue) { pRoot = NULL; return; } else { pRoot = new BinaryTreeNode(); pRoot->m_nValue = nNodeValue; CreateBinaryTree(pRoot->m_pLeft); CreateBinaryTree(pRoot->m_pRight); } } void PrintInOrder(BinaryTreeNode *&pRoot)//中序遍歷二叉樹 { if (pRoot != NULL) { PrintInOrder(pRoot->m_pLeft); cout << pRoot->m_nValue << " "; PrintInOrder(pRoot->m_pRight); } } void PrintDoubleListFromLeftToRight(BinaryTreeNode *pRoot)//從左到右打印雙向鏈表 { if (pRoot == NULL) { return; } BinaryTreeNode *pNode = pRoot; while (pNode != NULL) { cout << pNode->m_nValue << " "; pNode = pNode->m_pRight; } cout << endl; } void PrintDoubleListFromRightToLeft(BinaryTreeNode *pRoot)//從右向左打印雙向鏈表 { if (pRoot == NULL) { return; } BinaryTreeNode *pNode = pRoot; while (pNode->m_pRight != NULL) { pNode = pNode->m_pRight; } while (pNode != NULL) { cout << pNode->m_nValue << " "; pNode = pNode->m_pLeft; } cout << endl; } int _tmain(int argc, _TCHAR* argv[]) { BinaryTreeNode *pRoot = NULL; CreateBinaryTree(pRoot); PrintInOrder(pRoot);//4 6 8 10 12 14 16 cout << endl; BinaryTreeNode *pDoubleListHead = ConvertBSTToDoubleList(pRoot); PrintDoubleListFromLeftToRight(pDoubleListHead);//4 6 8 10 12 14 16 PrintDoubleListFromRightToLeft(pDoubleListHead);//16 14 12 10 8 6 4 system("pause"); return 0; }