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) return NULL;
if(!head->next){TreeNode *p=new TreeNode(head->val); return p;}//不要漏了这个
ListNode *cur=findhalf(head);
// if(cur){
TreeNode *tree=new TreeNode(cur->val);
tree->left=sortedListToBST(head);
tree->right=sortedListToBST(cur->next);
return tree;
//}
return NULL;
}
ListNode* findhalf(ListNode* head){
// if(!head) return NULL;
ListNode *slow=head,*fast=head,*pre=head;
while(fast&&fast->next){
pre=slow;
slow=slow->next;
fast=fast->next->next;
}
pre->next=NULL;
return slow;
}
};