LoveFM

导航

BinaryTreeConvertToDoubleList____<1>

  1 /*
2 * BtreeToDoublelist.cpp
3
4 * 思路:我们可以中序遍历整棵树。按照这个方式遍历树,比较小的结点先访问。
5 * 如果我们每访问一个结点,假设之前访问过的结点已经调整成一个排序双向链表,
6 * 我们再把调整当前结点的指针将其链接到链表的末尾。当所有结点都访问过之后,
7 * 整棵树也就转换成一个排序双向链表了。
8 */
9
10 using namespace std;
11 #include <stdio.h>
12 #include <iostream>
13
14 struct BSTreeNode
15 {
16 int m_nValue; // value of node
17 BSTreeNode *m_pLeft, *m_pRight; // left,right child of node
18 };
19
20 typedef BSTreeNode DoubleList;
21
22 DoubleList * pHead;
23 DoubleList * pListIndex;
24
25 // 创建二元查找树
26 void AddBSTreeNode(BSTreeNode * & pCurrent, int value)
27 {
28 if (NULL == pCurrent){
29 BSTreeNode * pBSTree = new BSTreeNode();
30 pBSTree->m_pLeft = NULL;
31 pBSTree->m_pRight = NULL;
32 pBSTree->m_nValue = value;
33 pCurrent = pBSTree;
34 }
35 else{
36 if ((pCurrent->m_nValue) > value){
37 AddBSTreeNode(pCurrent->m_pLeft, value);
38 }
39 else if ((pCurrent->m_nValue) < value){
40 AddBSTreeNode(pCurrent->m_pRight, value);
41 }
42 else {
43 //cout<<"重复加入节点"<<endl;
44 }
45 }
46 }
47
48
49 // 二叉树转换成 list
50 void ConvertToDoubleList(BSTreeNode * pCurrent)
51 {
52 pCurrent->m_pLeft = pListIndex;
53
54 if (NULL != pListIndex){
55 pListIndex->m_pRight = pCurrent;
56 }
57 else{
58 pHead = pCurrent;
59 }
60 pListIndex = pCurrent;
61
62 cout<<pCurrent->m_nValue<<endl;
63 }
64
65 // 遍历二元查找树:中序
66 void TraverseBSTree(BSTreeNode * pCurrent)
67 {
68 if (NULL == pCurrent){
69 return;
70 }
71 if (NULL != pCurrent->m_pLeft){
72 TraverseBSTree(pCurrent->m_pLeft);
73 }
74 // 节点接到链表尾部
75 ConvertToDoubleList(pCurrent);
76 // 右子树为空
77 if (NULL != pCurrent->m_pRight){
78 TraverseBSTree(pCurrent->m_pRight);
79 }
80 }
81
82
83 int main()
84 {
85 BSTreeNode * pRoot = NULL;
86 pListIndex = NULL;
87 pHead = NULL;
88
89 AddBSTreeNode(pRoot, 10);
90 AddBSTreeNode(pRoot,14);
91 AddBSTreeNode(pRoot,6);
92 AddBSTreeNode(pRoot,12);
93 AddBSTreeNode(pRoot,8);
94 AddBSTreeNode(pRoot,4);
95 AddBSTreeNode(pRoot, 16);
96
97 TraverseBSTree(pRoot);
98
99 return 0;
100 }

posted on 2011-11-29 20:12  LoveFM  阅读(485)  评论(0编辑  收藏  举报