/**
* 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) {
return makeBST(head, NULL);
}
TreeNode* makeBST(ListNode* head, ListNode* tail) {
ListNode *fast = head, *slow = head;
if (head == tail) return NULL;
while(fast != tail && fast->next != tail) {
fast = fast->next->next;
slow = slow->next;
}
TreeNode* result = new TreeNode(slow->val);
result->left = makeBST(head, slow);
result->right = makeBST(slow->next, tail);
return result;
}
};