把二元查找树转变成排序的双向链表()
题目:
输入一棵二元查找树,将该转换成个排序的双向链表。
要求不能创建任何新的结点,只调整指针向。
#include<stdio.h>
#include<stdlib.h>
typedef struct _BitTree {
struct _BitTree * left;
struct _BitTree * right;
int value;
}BitTree;
void AddNode( BitTree ** root, int value) {
BitTree *p;
if( *root == NULL) {
*root = (BitTree *)malloc(sizeof(BitTree));
if( *root == NULL)
return ;
(*root)->left = NULL;
(*root)->right = NULL;
(*root)->value = value;
return;
}
p = *root;
while(1) {
if(p->value > value){
if(p->left == NULL) {
p->left = (BitTree *)malloc(sizeof(BitTree ));
if(p->left == NULL)
printf(“malloc left error\n”);
p->left->value = value;
p->left->left = NULL;
p->left->right = NULL;
return;
}
p = p->left;
}else if(p->value < value) {
if(p->right == NULL) {
p->right = (BitTree *) malloc ( sizeof ( BitTree ));
if( p->right == NULL)
printf (“malloc right error\n”);
p->right->value = value;
p->right->left = NULL;
p->right->right = NULL;
return;
}
p = p->right;
}else {
printf(“congfu\n”);
return;
}
}
return;
}
void ConvertTree(BitTree ** head, BitTree ** tail, BitTree* root) {
BitTree *h = NULL, *t = NULL;
if(root == NULL)
return;
ConvertTree ( &h, &t, root->left);
if(t != NULL) {
root->left = t;
t->right = root;
*head = h;
}
h = NULL;
t = NULL;
ConvertTree (&h, &t, root->right);
if(h != NULL) {
root->right = h;
h->left = root;
*tail = t;
}
if(h == NULL)
*head = root;
if(t == NULL)
*tail = root;
}
int main(int argc, char *argv[]) {
BitTree *tree = NULL, *head = NULL, *tail = NULL;
AddNode(&tree, 10);
AddNode(&tree, 6);
AddNode(&tree, 14);
AddNode(&tree, 4);
AddNode(&tree, 3);
AddNode(&tree, 5);
AddNode(&tree, 8);
AddNode(&tree, 7);
AddNode(&tree, 9);
AddNode(&tree, 12);
AddNode(&tree, 11);
AddNode(&tree, 13);
AddNode(&tree, 15);
ConvertTree(&head, &tail, tree);
while(tree->left != NULL)
tree = tree->left;
while(tree->right != NULL) {
printf(“%d “, tree->value);
tree = tree->right;
}
return 0;
}