二叉搜索树转化为有序双向链表(C语言)

 

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef struct BSTreeNode
 5 {
 6     int m_nValue;
 7     BSTreeNode *m_pLeft; 
 8     BSTreeNode *m_pRight; 
 9 }BSTreeNode;
10  
11 BSTreeNode *pHead=NULL;
12 BSTreeNode *pIndex=NULL;
13 
14 void addBSTreeNode(BSTreeNode* &pCurrent,int value)
15 {
16     if (pCurrent==NULL)
17     {
18         BSTreeNode* pBSTree = NULL;
19         pBSTree    = (BSTreeNode*)malloc(sizeof(BSTreeNode));
20         pBSTree->m_nValue=value;
21         pBSTree->m_pLeft=NULL;
22         pBSTree->m_pRight=NULL;
23         pCurrent=pBSTree;
24     }
25     else if(pCurrent->m_nValue<value)
26     {
27         addBSTreeNode(pCurrent->m_pRight,value);
28     }
29     else if(pCurrent->m_nValue>value)
30     {
31         addBSTreeNode(pCurrent->m_pLeft,value);
32     }
34 }
35 
36 void convertToDoubleList(BSTreeNode* pCurrent)
37 {
38     pCurrent->m_pLeft=pIndex;//使当前结点的左指针指向双向链表中最后一个结点
39     if (NULL==pIndex)//若最后一个元素不存在,此时双向链表尚未建立,因此将当前结点设为双向链表头结点
40     {
41         pHead=pCurrent;
42     }
43     else//使双向链表中最后一个结点的右指针指向当前结点
44     {
45         pIndex->m_pRight=pCurrent;
46     }
48     pIndex=pCurrent;//将当前结点设为双向链表中最后一个结点
50     printf("%d ",pCurrent->m_nValue);
52 }
53 
54 void inOrderBSTree(BSTreeNode* pBSTree)
55 {
57     if (NULL==pBSTree)
58     {
59         return;
60     }
61     if (NULL!=pBSTree->m_pLeft)
62     {
63         inOrderBSTree(pBSTree->m_pLeft);
64     }
65  
66     convertToDoubleList(pBSTree);
67  
68     if (NULL!=pBSTree->m_pRight)
69     {
70         inOrderBSTree(pBSTree->m_pRight);
71     }
73 }
74 
76 int main()
77 {
79     BSTreeNode *pRoot=NULL;
80     addBSTreeNode(pRoot,10);
81     addBSTreeNode(pRoot,6);
82     addBSTreeNode(pRoot,14);
83     addBSTreeNode(pRoot,4);
84     addBSTreeNode(pRoot,8);
85     addBSTreeNode(pRoot,12);
86     addBSTreeNode(pRoot,16);
87     inOrderBSTree(pRoot);
88     return 0;
89 }

 

posted @ 2016-08-27 15:45  Walker_Lee  阅读(324)  评论(0编辑  收藏  举报