題目:輸入一顆二叉搜索樹,將該二叉搜索樹轉換爲一個排序的雙向鏈表。要求不能建立ios
任何新的結點,只能調整樹種結點指針的指向。好比輸入下圖的二叉搜索樹,則輸出轉換spa
後的雙向排序鏈表。指針
1 10 2 / \ 3 6 14 4 / \ / \ 5 4 8 12 16
轉換後的雙向排序鏈表爲:code
1 4<--->6<--->8<--->10<--->12<--->14<--->16
首先 要明白二叉搜索樹是根結點大於左子結點,小於右子結點 blog
然而要讓轉換後的雙向鏈表基本有序,則應該中序遍歷該二叉樹排序
遍歷的時候將樹當作三部分:值爲10的根結點,根結點值爲6的左遞歸
子樹,根結點值爲14的右子樹。根據排序鏈表的定義。值爲10的ci
結點將和左子樹的最大的結點連接起來,同時該結點還要和右子樹io
最小的結點連接起來。ast
然而對於左子樹和右子樹,遞歸上述步驟便可。
代碼實現以下:
1 #include <iostream> 2 using namespace std; 3 4 struct BinaryTreeNode 5 { 6 int m_nValue; 7 BinaryTreeNode* m_pLeft; 8 BinaryTreeNode* m_pRight; 9 }; 10 11 void ConvertNode(BinaryTreeNode* pNode,BinaryTreeNode** pLastNodeInlist) 12 { 13 if(pNode==NULL) 14 return; 15 16 BinaryTreeNode *pCurrent = pNode; 17 18 if(pCurrent->m_pLeft!=NULL) 19 ConvertNode(pCurrent->m_pLeft,pLastNodeInlist); 20 21 pCurrent->m_pLeft=*pLastNodeInlist; 22 23 if(*pLastNodeInlist!=NULL) 24 (*pLastNodeInlist)->m_pRight=pCurrent; 25 26 *pLastNodeInlist=pCurrent; 27 28 if(pCurrent->m_pRight!=NULL) 29 ConvertNode(pCurrent->m_pRight,pLastNodeInlist); 30 } 31 32 33 34 BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree) 35 { 36 BinaryTreeNode *pLastNodeInList = NULL; 37 ConvertNode(pRootOfTree,&pLastNodeInList); 38 39 BinaryTreeNode *pHeadOfList = pLastNodeInList; 40 while(pHeadOfList != NULL&&pHeadOfList->m_pLeft!=NULL) 41 pHeadOfList = pHeadOfList->m_pLeft; 42 43 return pHeadOfList; 44 } 45 46 void CreateTree(BinaryTreeNode** Root) 47 { 48 int data; 49 cin>>data; 50 if(data==0) 51 { 52 *Root=NULL; 53 return ; 54 } 55 else 56 { 57 *Root=(BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); 58 (*Root)->m_nValue=data; 59 CreateTree(&((*Root)->m_pLeft)); 60 CreateTree(&((*Root)->m_pRight)); 61 } 62 } 63 64 void PrintTreeInOrder(BinaryTreeNode* Root) 65 { 66 if(Root==NULL) 67 { 68 return; 69 } 70 cout<<Root->m_nValue<<" "; 71 PrintTreeInOrder(Root->m_pLeft); 72 PrintTreeInOrder(Root->m_pRight); 73 74 } 75 76 void PrintTheLinkList(BinaryTreeNode *Head) 77 { 78 cout<<"從前日後變量該雙向鏈表: "; 79 while(Head->m_pRight!=NULL) 80 { 81 cout<<Head->m_nValue<<" "; 82 Head=Head->m_pRight; 83 } 84 cout<<Head->m_nValue<<" "; 85 cout<<endl; 86 BinaryTreeNode *Last=Head; 87 cout<<"從後往前變量該雙向鏈表: "; 88 while(Last!=NULL) 89 { 90 cout<<Last->m_nValue<<" "; 91 Last=Last->m_pLeft; 92 } 93 } 94 95 int main() 96 { 97 BinaryTreeNode* Root; 98 CreateTree(&Root); 99 cout<<"The InOrderOfTree: "; 100 PrintTreeInOrder(Root); 101 cout<<endl; 102 BinaryTreeNode* HeadOfLinkList; 103 HeadOfLinkList=Convert(Root); 104 cout<<endl; 105 PrintTheLinkList(HeadOfLinkList); 106 cout<<endl; 107 system("pause"); 108 return 0; 109 }
運行截圖: