您的位置:首页 > 其它

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

2013-04-01 09:15 260 查看
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \

4 81216



solution:
#include <iostream>
using namespace std;
typedef struct BiNode
{
struct BiNode* lchild;
struct BiNode* rchild;
int data;
}BiNode,*BiTree;
class BiTreeToDList
{
private:
BiNode* listHead;
BiNode* pList;
public:
BiTreeToDList();
void createTree(BiTree & root);
void inorder(BiTree root);
void convert(BiNode* p);
};
inline BiTreeToDList():listHead(NULL),pList(NULL)
{
}
void BiTreeToDList::createTree(BiTree & root)
{
int data;
cout<<"please input data:"<<endl;
cin>>data;
if('#'==data)
return ;
BiNode* node = new BiNode;
root = node;
try
{
node->data = data;
node->lchild = NULL;
node->rchild = NULL;
throw "create node failer";
}catch(char* str)
{
cout<<str<<endl;
exit(-1);
}
createTree(root->lchild);
createTree(root->rchild);
};
void BiTreeToDList::convert(BiNode* p)
{
p->lchild = pList;
if(NULL!=pList)
{
pList->rchild = p;
}
else
{
listHead = p;
}
pList = p;
};
void BiTreeToDList::inorder(BiTree root)
{
if(NULL==root)
return ;
inorder(root->lchild);
convert(root);
inorder(root->rchild);
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息