#include <stdio.h>
#include <iostream>
using namespace std;
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
typedef BSTreeNode DoubleList;
DoubleList * pHead;
// 创建二元查找树
void createBinarySearchTree(BSTreeNode * & pCurrent, int value)
{
if (NULL == pCurrent)
{
BSTreeNode * pBSTree = new BSTreeNode();
pBSTree->m_pLeft = NULL;
pBSTree->m_pRight = NULL;
pBSTree->m_nValue = value;
pCurrent = pBSTree;
}
else
{
if ((pCurrent->m_nValue) > value)
{//如果比当前节点值小,则放到左子树
createBinarySearchTree(pCurrent->m_pLeft, value);
}
else if ((pCurrent->m_nValue) < value)
{//如果比当前节点值大,则放到右子树
createBinarySearchTree(pCurrent->m_pRight, value);
}
else
{//否则提示重复插入了。
cout<<"重复加入节点"<<endl;
}
}
}
//采用中序遍历的方法
void ConvertNode(BSTreeNode *pNode,BSTreeNode *&pLastNodeInList)
{
if(pNode == NULL)
{
return ;
}
BSTreeNode *pCurrent = pNode;
//先递归遍历左子树
if(pCurrent->m_pLeft != NULL)
{
ConvertNode(pCurrent->m_pLeft,pLastNodeInList);
}
//把左子树遍历结果连接到当前节点的左边
pCurrent->m_pLeft = pLastNodeInList;
if(pLastNodeInList != NULL)
{
pLastNodeInList->m_pRight = pCurrent;
}
pLastNodeInList = pCurrent;
if(pCurrent->m_pRight != NULL)
{
ConvertNode(pCurrent->m_pRight,pLastNodeInList);
}
}
//
BSTreeNode *Convert(BSTreeNode *pHeadOfTree)
{
BSTreeNode *pLastNodeInList = NULL;
ConvertNode(pHeadOfTree,pLastNodeInList);
//取得
BSTreeNode *pHeadOfList = pLastNodeInList;
while(pHeadOfList && pHeadOfList->m_pLeft)
{
pHeadOfList = pHeadOfList->m_pLeft;
}
return pHeadOfList;
}
int main()
{
BSTreeNode * pRoot = NULL;
pHead = NULL;
createBinarySearchTree(pRoot, 10);
createBinarySearchTree(pRoot, 4);
createBinarySearchTree(pRoot, 6);
createBinarySearchTree(pRoot, 8);
createBinarySearchTree(pRoot, 12);
createBinarySearchTree(pRoot, 14);
createBinarySearchTree(pRoot, 15);
createBinarySearchTree(pRoot, 16);
pHead = Convert(pRoot);
//从最左侧开始打印双向链表
cout << "从左向右打印:";
DoubleList *p = pHead;
while(p != NULL)
{
cout << p->m_nValue<<" ";
p= p->m_pRight;
}
//从最右侧开始打印双向链表
cout << endl <<"从右向左打印:";
while(pHead->m_pRight != NULL)
{
pHead= pHead->m_pRight;
}
while(pHead != NULL)
{
cout << pHead->m_nValue<<" ";
pHead = pHead->m_pLeft;
}
cout << endl;
return 0;
}