题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
#include <iostream>
#include <string>
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 struct BSTreeNode DoubleList;;
DoubleList * pHead;
DoubleList * pListIndex;
void ConvertToDoubleList(BSTreeNode *pCurrent);
void AddBSTree(BSTreeNode *&pCurrent,int value)
{
if(pCurrent == NULL)
{
BSTreeNode * pBSNode = new BSTreeNode();
pBSNode->m_pLeft = NULL;
pBSNode->m_pRight = NULL;
pBSNode->m_nValue = value;
pCurrent = pBSNode;
}
else
{
if(pCurrent->m_nValue > value)
AddBSTree(pCurrent->m_pLeft,value);
else if (pCurrent->m_nValue < value)
AddBSTree(pCurrent->m_pRight,value);
}
}
void InoderTraverse(BSTreeNode *pCurrent)
{
if (pCurrent == NULL)
return ;
if(pCurrent->m_pLeft != NULL)
InoderTraverse(pCurrent->m_pLeft);
//二叉树——链表转换
ConvertToDoubleList(pCurrent);
if(pCurrent->m_pRight != NULL)
InoderTraverse(pCurrent->m_pRight);
}
void ConvertToDoubleList(BSTreeNode *pCurrent)
{
pCurrent->m_pLeft = pListIndex;
if(pListIndex == NULL)
{
pHead = pCurrent;
}
else
{
pListIndex->m_pRight = pCurrent;
}
pListIndex = pCurrent;
cout<<pCurrent->m_nValue<<" ";
}