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==NULL)
return NULL;
return recurbuild(head);
}
TreeNode *recurbuild(ListNode* head)
{
if(head==NULL)
return NULL;
if(head->next==NULL)
{
return new TreeNode(head->val);
}
ListNode* sav=head;
ListNode* mid=head;
ListNode* pre=mid;
while(head&&head->next)
{
head=head->next->next;
pre=mid;
mid=mid->next;
}
pre->next=NULL;
TreeNode* temp=new TreeNode(mid->val);
temp->left=sortedListToBST(sav);
temp->right=sortedListToBST(mid->next);
return temp;
}
};