Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
Code:
<span style="font-size:14px;">/**
* 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) {
if (!head) return NULL;
if (!head->next) return new TreeNode(head->val);
ListNode *fast = head->next->next, *slow = head;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
slow->next = NULL;
TreeNode *root = new TreeNode(fast->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(fast->next);
return root;
}
};</span>