/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
vector<int> num;
if (head == NULL)
return NULL;
while (head){
num.push_back(head->val);
head = head->next;
}
return sortListToBST(0, num.size()-1, num);
}
TreeNode *sortListToBST(int start, int end, vector<int> &num){
if (start > end)
return NULL;
int mid = (end + start)/2 + (end + start)%2;
TreeNode *root = new TreeNode(num[mid]);
root->left = sortListToBST(start, mid-1, num);
root->right = sortListToBST(mid+1, end, num);
return root;
}
};