Use the fast slow method to find the mid point of the list and make it the root. Then do it recursively on both sides.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head)
return NULL;
return helper(head,NULL);
}
TreeNode* helper(ListNode* start,ListNode* end)
{
if(start==end)
return NULL;
ListNode *slow,*fast;
slow=fast=start;
while(fast->next!=end&&fast->next->next!=end)
{
slow=slow->next;
fast=fast->next->next;
}
TreeNode *root=new TreeNode(slow->val);
root->left=helper(start,slow);
root->right=helper(slow->next,end);
return root;
}
};