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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == NULL)return NULL;
ListNode *fast = head, *slow = head, *preSlow = NULL;
while(fast->next && fast->next->next)
{
fast = fast->next->next;
preSlow = slow;
slow = slow->next;
}
TreeNode *res = new TreeNode(slow->val);
fast = slow->next;
delete slow;
if(preSlow != NULL)
{
preSlow->next = NULL;
res->left = sortedListToBST(head);
}
res->right = sortedListToBST(fast);
return res;
}
};