题目:把一个有序的链表转换为BST
思路:和上面的一样,只不过这里需要注意查找链表中间点的方法
程序中只有最后三个函数有用
#include <iostream>
using namespace std;
/*
将一个有序的链表 转换为二叉平衡树 BST
*/
/*
思路:这个和上面将有序的数组装换为BST非常相似
都是采用同样的方法 只是这里查找链表的中间节点
是一个很麻烦的事情
*/
typedef struct list_node List;
typedef struct bst_node BST;
struct list_node
{
int value;
List* next;
};
struct bst_node
{
int value;
BST* left;
BST* right;
};
void print_list(List* list)
{
List* tmp=list;
while(tmp != NULL)
{
cout<<tmp->value<<endl;
tmp = tmp->next;
}
}
/*
初始化List 将从1~n的数字插入到链表中
*/
void Init_List(List*& head,int* array,int n)
{
head = NULL;
List* tmp;
List* record;
for(int i=1;i<=n;i++)
{
tmp = new List;
tmp->next = NULL;
tmp->value = array[i-1];
if(head == NULL)
{
head = tmp;
record = head;
}
else
{
record->next = tmp;
record = tmp;
}
}
}
int Len_list(List* list)
{
if(list == NULL)
return 0;
else
return Len_list(list->next)+1;
}
void print_bintree(BST* root)
{
if(root != NULL)
{
print_bintree(root->left);
cout<<root->value<<endl;
print_bintree(root->right);
}
}
/*
从一个链表的头部和尾部找到中间节点 这里的tail是组成区间的链表的最后一个节点的下一个节点
*/
List* getMid(List* list,List* head,List* tail)
{
if(head == NULL)
return NULL;
if(head == tail)
return NULL;
List* slow = head;
List* fast = head->next;
while(fast!=NULL && fast != tail)
{
slow = slow->next;
fast = fast->next;
if(fast != NULL && fast != tail)
fast = fast->next;
}
return slow;
}
BST* helper(List* list,List* head,List* tail)
{
BST* root = NULL;
if(head == NULL)
return NULL;
else
{
List* mid = getMid(list,head,tail);
if(mid != NULL)
{
BST* root = new BST;
root->left = NULL;
root->right = NULL;
root->value = mid->value;
root->left = helper(list,head,mid);
root->right = helper(list,mid->next,tail);
return root;
}
return NULL;
}
}
BST* ListCreateBST(List* list)
{
if(list == NULL)
return NULL;
return helper(list,list,NULL);
}
int main()
{
int array[15];
int i;
for(i=0;i<sizeof(array)/sizeof(int);i++)
array[i] = i+1;
List* list;
Init_List(list,array,sizeof(array)/sizeof(int));
BST* root = ListCreateBST(list);
print_bintree(root);
return 0;
}