/**
* 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 == NULL) {
return NULL;
}
vector<int> nodes;
ListNode* curr = head;
while (curr) {
nodes.push_back(curr->val);
curr = curr->next;
}
return buildTree(nodes, 0, nodes.size() - 1);
}
private:
TreeNode* buildTree(vector<int> &nodes, int left, int right){
if(left > right) {
return NULL;
}
int mid = (left + right) / 2;
TreeNode* node = new TreeNode(nodes[mid]);
node->left = buildTree(nodes, left, mid - 1);
node->right = buildTree(nodes, mid + 1, right);
return node;
}
};