把二元查找树转变成排序的双向链表

题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
   10
   / /
  6  14
/ / / /
4  8 12 16
转换成双向链表:4=6=8=10=12=14=16
  思路:二叉查找树按中序遍历得到的数据是按顺序排列的,所以要按照中序遍历的顺序把二叉树转换成链表;二叉树每一个结点有两个指针left,right,和链表的前驱和后继对应的指针正好对应。
  代码:
 1 #include <iostream>
 2 using namespace std;
 3 
 4 struct BSTreeNode
 5 {
 6     int m_nValue; // value of node
 7     BSTreeNode *m_pLeft; // left child of node
 8     BSTreeNode *m_pRight; // right child of node
 9 };
10 
11 typedef BSTreeNode DoubleList;
12 DoubleList * pHead;
13 DoubleList * pListIndex;
14 
15 void convertToDoubleList(BSTreeNode * pCurrent);
16 // 创建二元查找树
17 void addBSTreeNode(BSTreeNode * & pCurrent, int value)
18 {
19     if (NULL == pCurrent)
20     {
21         BSTreeNode * pBSTree = new BSTreeNode();
22         pBSTree->m_pLeft = NULL;
23         pBSTree->m_pRight = NULL;
24         pBSTree->m_nValue = value;
25         pCurrent = pBSTree;
26     }
27     else
28     {
29         if ((pCurrent->m_nValue) > value)
30         {
31             addBSTreeNode(pCurrent->m_pLeft, value);
32         }
33         else if ((pCurrent->m_nValue) < value)
34         {
35             addBSTreeNode(pCurrent->m_pRight, value);
36         }
37         else
38         {
39             cout<<"不能重复加入相同节点"<<endl;
40         }
41     }
42 }
43 
44 // 遍历二元查找树  中序
45 void ergodicBSTree(BSTreeNode * pCurrent)
46 {
47     if (NULL == pCurrent)
48     {
49         return;
50     }
51     if (NULL != pCurrent->m_pLeft)
52     {
53         ergodicBSTree(pCurrent->m_pLeft);
54     }
55     // 节点接到链表尾部
56     convertToDoubleList(pCurrent);
57     // 右子树为空
58     if (NULL != pCurrent->m_pRight)
59     {
60         ergodicBSTree(pCurrent->m_pRight);
61     }
62 }
63 
64 // 二叉树转换成list
65 void  convertToDoubleList(BSTreeNode * pCurrent)
66 {
67     pCurrent->m_pLeft = pListIndex;//left相当于前驱指针,right相当于后继指针
68     if (NULL != pListIndex)
69     {
70         pListIndex->m_pRight = pCurrent;
71     }
72     else
73     {
74         pHead = pCurrent;//头结点即为中序遍历的第一个结点,本例中即为4结点
75     }
76     pListIndex = pCurrent;
77     cout<<pCurrent->m_nValue<<endl;
78 }
79 
80 int main()
81 {
82     BSTreeNode * pRoot = NULL;
83     pListIndex = NULL;//用于建立链表
84     pHead = NULL;//链表头结点
85     addBSTreeNode(pRoot, 10);
86     addBSTreeNode(pRoot, 4);
87     addBSTreeNode(pRoot, 6);
88     addBSTreeNode(pRoot, 8);
89     addBSTreeNode(pRoot, 12);
90     addBSTreeNode(pRoot, 14);
91     addBSTreeNode(pRoot, 15);
92     addBSTreeNode(pRoot, 16);
93     ergodicBSTree(pRoot);
94     return 0;
95 }

仅供参考。

posted @ 2013-04-27 16:58  楠楠IT  阅读(593)  评论(0编辑  收藏  举报