Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* 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;
if (head->next == NULL) return (new TreeNode(head->val));
int len = 0;
ListNode *cur = head;
while (cur) {
cur = cur->next;
++len;
}
return sortedListToBST(head, len);
}
TreeNode* sortedListToBST(ListNode* head, int len) {
if (head == NULL || len == 0) return NULL;
int mid_index = len / 2;
int left_len = len / 2;
int right_len = len / 2 - 1 + len % 2;
ListNode *mid = head;
for (int i = 0; i < mid_index; ++i)
mid = mid->next;
ListNode *right = mid->next;
TreeNode *root = new TreeNode(mid->val);
if (left_len)
root->left = sortedListToBST(head, left_len);
if (right_len)
root->right = sortedListToBST(right, right_len);
return root;
}
};