思路:和上面的思想一样,只不过注意找到链表的中间节点的方法
void Inorder(BinTree* root)
{
if(root == NULL)
return ;
Inorder(root->left);
cout<<root->value<<endl;
Inorder(root->right);
}
List* FindMid(List*& list,List*& head,List* tail)
{
List* fast = head;
List* slow = head;
while(fast != NULL && fast->next != tail)
{
slow = slow->next;
fast = fast->next;
if(fast != NULL && fast->next != tail)
fast=fast->next;
}
return slow;
}
BinTree* helper(List*& root,List*& head,List*& tail)
{
BinTree* node = NULL;
if(head == tail || head == NULL)
return node;
List* mid = FindMid(root,head,tail);
List* next = mid->next;
node = new BinTree;
node->value = mid->value;
node->left = node->right = NULL;
node->left = helper(root,head,mid);
node->right = helper(root,next,tail);
return node;
}
BinTree* ConvertBST(List*& list)
{
BinTree* root = NULL;
if(list ==NULL)
return root;
List* head=list;
List* tail=NULL;
root = helper(list,head,tail);
return root;
}
int main()
{
int array[]={1,2,3,4,5,6,7,8,9,10};
//int array[]={1,4,3,2,5,2};
List* list;
Init_List(list,array,sizeof(array)/sizeof(int));
BinTree* root = ConvertBST(list);
Inorder(root);
return 0;
}Convert Sorted List to Binary Search Tree--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44871893