/*
采用快慢指针
slow指针每次都一步
fast指针每次走两步,当fast到达r的位置时候slow为中点
*/
class Solution {
public:
TreeNode* dfs(ListNode* l,ListNode* r)
{
if(l == r) return NULL;
ListNode* fast=l;
ListNode* slow=l;
while(fast != r && fast->next != r)
{
fast=fast->next->next;
slow=slow->next;
}
TreeNode* root=new TreeNode(slow->val);
root->left=dfs(l,slow);
root->right=dfs(slow->next,r);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
TreeNode* root=dfs(head,NULL);
return root;
}
};