简单的取中点,分成两半
/**
* 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;
ListNode* fast = head;
ListNode* slow = head;
ListNode* r = NULL;
while(fast->next && fast->next->next)
{
r = slow;
slow = slow->next;
fast = fast->next->next;
}
if(r)
r->next = NULL;
TreeNode * root = new TreeNode(slow->val);
if(head == slow)
root->left = sortedListToBST(NULL);
else
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
};