class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
ListNode* tail = head;
ListNode* middle = head;
while(tail!=NULL&&tail->next!=NULL){
tail = tail->next;
}
return sortedListToBST(head,tail);
}
TreeNode* sortedListToBST(ListNode* head,ListNode* tail) {
if(head == NULL) return NULL;
if(head==tail) return new TreeNode(head->val);
ListNode* tailTemp = head;
ListNode* middle = head;
ListNode* beforeMiddel = new ListNode(-100);
beforeMiddel->next = middle;
while(tailTemp!=NULL && tailTemp!=tail && tailTemp!=tail->next){
tailTemp = tailTemp->next->next;
middle = middle->next;
beforeMiddel = beforeMiddel->next;
//if(beforeMiddel!=NULL && middle!=NULL && tailTemp!=NULL)
//cout<<beforeMiddel->val<<middle->val<<tailTemp->val<<endl;
}
TreeNode* root = new TreeNode(middle->val);//if(middle!=NULL && tail!=NULL) cout<<head->val<<" "<<beforeMiddel->val<<endl;
root->left = sortedListToBST(head,beforeMiddel);
if(middle!=tail){
root->right = sortedListToBST(middle->next,tail);
//cout<<root->right->val;
}
return root;
}
};
public:
TreeNode* sortedListToBST(ListNode* head) {
ListNode* tail = head;
ListNode* middle = head;
while(tail!=NULL&&tail->next!=NULL){
tail = tail->next;
}
return sortedListToBST(head,tail);
}
TreeNode* sortedListToBST(ListNode* head,ListNode* tail) {
if(head == NULL) return NULL;
if(head==tail) return new TreeNode(head->val);
ListNode* tailTemp = head;
ListNode* middle = head;
ListNode* beforeMiddel = new ListNode(-100);
beforeMiddel->next = middle;
while(tailTemp!=NULL && tailTemp!=tail && tailTemp!=tail->next){
tailTemp = tailTemp->next->next;
middle = middle->next;
beforeMiddel = beforeMiddel->next;
//if(beforeMiddel!=NULL && middle!=NULL && tailTemp!=NULL)
//cout<<beforeMiddel->val<<middle->val<<tailTemp->val<<endl;
}
TreeNode* root = new TreeNode(middle->val);//if(middle!=NULL && tail!=NULL) cout<<head->val<<" "<<beforeMiddel->val<<endl;
root->left = sortedListToBST(head,beforeMiddel);
if(middle!=tail){
root->right = sortedListToBST(middle->next,tail);
//cout<<root->right->val;
}
return root;
}
};