输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
#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
};
//正好熟悉下指针和引用的用法,可以把一下的代码自己把引用去了试试效果
void addNode(BSTreeNode *&pCurrent,int value);
void initTree(BSTreeNode * &pRoot);
void inOrderBSTree(BSTreeNode* pBSTree);
void convertToDoubleList(BSTreeNode* pCurrent);
BSTreeNode *pHead=NULL;//头指针
BSTreeNode *pIndex=NULL; //尾指针
int main()
{
BSTreeNode *pRoot=NULL;
initTree(pRoot);
inOrderBSTree(pRoot);
BSTreeNode *tmp(pHead);
//从头遍历
while(tmp!=NULL){
cout<<tmp->m_nValue<<" ";
tmp=tmp->m_pRight;
}
cout<<endl;
//从尾遍历
BSTreeNode *tmp2(pIndex);
while(tmp2!=NULL){
cout<<tmp2->m_nValue<<" ";
tmp2=tmp2->m_pLeft;
}
cout<<endl;
system("pause");
return 0;
}
void addNode(BSTreeNode *&pCurrent,int value)
{
if (pCurrent==NULL)
{
BSTreeNode* pBSTree=new BSTreeNode();
pBSTree->m_nValue=value;
pBSTree->m_pLeft=NULL;
pBSTree->m_pRight=NULL;
pCurrent=pBSTree;
}
else if (pCurrent->m_nValue<value)
{
addNode(pCurrent->m_pRight,value);
}
else if (pCurrent->m_nValue>value)
{
addNode(pCurrent->m_pLeft,value);
}
else
{
cout<<"node repeated"<<endl;
}
}
void inOrderBSTree(BSTreeNode* pBSTree)
{
if (NULL==pBSTree)
{
return;
}
if (NULL!=pBSTree->m_pLeft)
{
inOrderBSTree(pBSTree->m_pLeft);
}
convertToDoubleList(pBSTree);
if (NULL!=pBSTree->m_pRight)
{
inOrderBSTree(pBSTree->m_pRight);
}
}
void convertToDoubleList(BSTreeNode* pCurrent)
{
pCurrent->m_pLeft=pIndex;
if (NULL==pIndex)
{
pHead=pCurrent;
}
else
{
pIndex->m_pRight=pCurrent;
}
pIndex=pCurrent;
// cout<<pCurrent->m_nValue<<" ";
}
void initTree(BSTreeNode * &pRoot){
addNode(pRoot,10);
addNode(pRoot,6);
addNode(pRoot,14);
addNode(pRoot,4);
addNode(pRoot,8);
addNode(pRoot,12);
addNode(pRoot,16);
}