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 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;
// find the mid element
ListNode *fast = head->next, *slow = head, *prev = NULL;
while (fast && fast->next)
{
fast = fast->next->next;
prev = slow;
slow = slow->next;
}
fast = slow->next; // head of the second list
if (prev) prev->next = NULL; // split list
else head = NULL; // no list in the left
TreeNode *root = new TreeNode(slow->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(fast);
return root;
}
};