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) {
return helper(head, NULL);
}
private:
TreeNode* helper(ListNode* start, ListNode* end){
if (start == end)
return NULL;
ListNode* faster = start;
ListNode* slower = start;
while (faster->next!=end&&faster->next->next!=end){
faster = faster->next->next;
slower = slower->next;
}
TreeNode* root = new TreeNode(slower->val);
root->left = helper(start, slower);//左开右闭空间
root->right = helper(slower->next, end);
return root;
}
};