# 28ms,easy-understand c++ solution

• ``````enter code here
class Solution {
public:
vector<int>nums;
TreeNode *root;
return NULL;
}
}
sortedListToBST(nums,root,0,nums.size()-1);
return root;
}
private:
void sortedListToBST(vector<int>&nums,TreeNode *&root,int beginIndex,int endIndex) {
if(beginIndex>endIndex) {
root=NULL;
return ;
}
int mid=(beginIndex+endIndex)/2;
root=new TreeNode(nums[mid]);
sortedListToBST(nums,root->left,beginIndex,mid-1);
sortedListToBST(nums,root->right,mid+1,endIndex);
}
};``````

• ``````TreeNode* sortedListToBST(ListNode* head) {
return NULL;
ListNode* dummy=new ListNode(-1);
ListNode* fast= dummy;
ListNode* slow = dummy;
ListNode* pre = slow;
//find middle node
while(fast && fast->next)
{
fast= fast->next->next;
pre = slow;
slow= slow->next;
}
//r is the right list
ListNode* r = slow->next;
pre->next= NULL;
//l is the left list
ListNode* l = dummy->next;
delete dummy;
TreeNode* root = new TreeNode(slow->val);
root->left = sortedListToBST(l);
root->right = sortedListToBST(r);
return root;
}
``````

This is how I solve it with C++;

• hi, maybe this is your correct code :)

``````class Solution {
public:
return NULL;
ListNode* pre = slow;
//find middle node
while(fast && fast->next)
{
fast= fast->next->next;
pre = slow;
slow= slow->next;
}
//r is the right list
ListNode* r = slow->next;
pre->next= NULL;
//l is the left list