题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。要求不能创建任何新的结点,只调整指针的指向。比如将二元查找树
10
/
6 14
/ /
4 81216
转换成双向链表4=6=8=10=12=14=16
1.思路
使用递归法。注意由于需要改变指针的指向,因此使用了指针引用。
2.代码
#include"iostream"
using namespace std;
struct Node // a node in the binary search tree
{
int value; // value of node
Node* left; // left child of node
Node* right; // right child of node
};
bool createList(Node* Head,Node* &left,Node* &right){
left=Head;
right=Head;
if(!Head)
return false;
else{
Node*l1,*r1,*l2,*r2;
l1=NULL;
r1=NULL;
l2=NULL;
r2=NULL;
if(createList(Head->left,l1,r1)){
Head->left=r1;
r1->right=Head;
left=l1;
}
if(createList(Head->right,l2,r2)){
Head->right=l2;
l2->left=Head;
right=r2;
}
return true;
}
}
void main(){
Node n4={4,NULL,NULL};
Node n5={8,NULL,NULL};
Node n6={18,NULL,NULL};
Node n2={6,&n4,&n5};
Node n3={14,NULL,&n6};
Node n1={10,&n2,&n3};
Node*Left=NULL;
Node*Right=NULL;
createList(&n1,Left,Right);
while(Left){
cout<<Left->value<<endl;
Left=Left->right;
}
}