您的位置:首页 > 其它

第10题 把二元查找树转换成排序的双向链表

2012-02-27 17:14 337 查看
题目:把二元查找树转换成排序的双向链表

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

10

/ \

6 14

/ \ / \

4 8 12 16

转成双向链表

4=6=8=12=14=16

关于此题, 有一篇非常详细的文档,把这个问题讲述的非常清楚,英文好的朋友可以看一下这篇文章

http://download.csdn.net/detail/stevemarbo/4094319

#include<stdio.h>
#include<stdlib.h>

// binary search tree
struct node {
int data;
struct node* small;
struct node* large;
};

void join(struct node* a, struct node* b) {
a->large = b;
b->small = a;
}

struct node* append(struct node* a, struct node* b) {
struct node* aLast;
struct node* bLast;

if(a == NULL)
return b;
if(b == NULL)
return a;

aLast = a->small;
bLast = b->small;

join(aLast, b);
join(bLast, a);

return a;
}

struct node* treeToList(struct node* root) {
struct node* aList;
struct node* bList;

if(root == NULL)
return NULL;

aList = treeToList(root->small);
bList = treeToList(root->large);

root->small = root;
root->large = root;

aList = append(aList, root);
bList = append(aList, bList);

return aList;
}

struct node* newNode(int data) {
struct node* n = (struct node *)malloc(sizeof(struct node));
n->data = data;
n->small = NULL;
n->large = NULL;

return n;
}

void treeInsert(struct node** rootRef, int data) {
struct node* root = *rootRef;
if(root == NULL)
*rootRef = newNode(data);
else {
if(data <= root->data)
treeInsert(&(root->small), data);
else
treeInsert(&(root->large), data);
}
}

void printList(struct node* head) {
struct node* current = head;

while(current != NULL) {
printf("%d ", current->data);
current = current->large;
if(current == head) break;
}
printf("\n");
}

int main() {
struct node* root = NULL;
struct node* head;

treeInsert(&root, 4);
treeInsert(&root, 2);
treeInsert(&root, 1);
treeInsert(&root, 3);
treeInsert(&root, 5);

head = treeToList(root);

printList(head);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐