您的位置:首页 > 其它

二叉查找树转双向链表(笔试)

2012-04-20 14:34 295 查看
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。

要求不能创建任何新的结点,只能调整指针的指向

10

/ \

6 14

/ \ / \

4 8 12 16

转换后成双向链表4<>6<>8<>10<>12<>14<>16。

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
struct Tree {
int data;
Tree *left;
Tree *right;
Tree(int d, Tree *l , Tree *r): data(d),left(l),right(r){}
};
Tree *MakeTree(int mydata) {
return new Tree(mydata,NULL, NULL);
}
void InsertTree(int mydata, Tree *&t) {
if(t == NULL) {
t = new Tree(mydata, NULL, NULL);
}
else if(mydata >= t->data){
InsertTree(mydata, t->right);
}else if(mydata < t->data)
InsertTree(mydata, t->left);
else{}
}
Tree *treeRoot, *tmp;
void visit(Tree *t) {
if(t == NULL)
return;
visit(t->left);

if(treeRoot == NULL) {
treeRoot = t;
tmp = treeRoot;
treeRoot->left = NULL;
treeRoot->right = NULL;
}
else {
tmp->right = t;
t->left = tmp;
tmp = tmp->right;
}
visit(t->right);
}
void MakeList(Tree *t) {
treeRoot = NULL;
visit(t);
for(; treeRoot != NULL; treeRoot = treeRoot->right) {
cout<<treeRoot->data<<" |  ";
}
cout<<endl;
}
void DeleteTree(Tree *root) {
if(root == NULL)
return;
DeleteTree(root->left);
DeleteTree(root->right);
delete root;
root = NULL;
}
int main() {
//Tree *root;
int n, a;
cin>>n;
cin>>a;
treeRoot = MakeTree(a);
for(int i = 1; i<n; i++) {
cin >>a;
InsertTree(a,treeRoot);
}
MakeList(treeRoot);
system("pause");
}


另外一个题目:二叉查找树转双向链表,不需要在原树上操作。

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
struct List {
int data;
List *prev;
List *next;
List(int d, List *p ,List *n):data(d), prev(p), next(n) {}
};
struct Tree {
int data;
Tree *left;
Tree *right;
Tree(int d, Tree *l , Tree *r): data(d),left(l),right(r){}
};
Tree *MakeTree(int mydata) {
return new Tree(mydata,NULL, NULL);
}
void InsertTree(int mydata, Tree *&t) {
if(t == NULL) {
t = new Tree(mydata, NULL, NULL);
}
else if(mydata >= t->data){
InsertTree(mydata, t->right);
}else if(mydata < t->data)
InsertTree(mydata, t->left);
else{}
}

List *list = NULL, *lst = NULL;
void visit(Tree *root) {
if(root == NULL)
return;
visit(root->left);
if(list == NULL){
list = new List(root->data,NULL, NULL);
lst = list;
return;
}

else {
List *tmp = new List(root->data, NULL, NULL);
lst->next = tmp;
tmp->prev = lst;
lst = lst->next;
}
//cout<<root->data;
visit(root->right);
}
void MakeList(Tree *root) {
visit(root);
for(; list!= NULL; list= list->next) {
cout<<list->data<<"    ";
}
cout<<endl;
}
void DeleteTree(Tree *root) {
if(root == NULL)
return;
DeleteTree(root->left);
DeleteTree(root->right);
delete root;
root = NULL;
}
int main() {
Tree *root;
int n, a;
cin>>n;
cin>>a;
root = MakeTree(a);
for(int i = 1; i<n; i++) {
cin >>a;
InsertTree(a,root);
}
MakeList(root);
system("pause");

}
/*
7
5 15 -30 10 -5 40 10
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: