class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
return create(head,NULL);
}
TreeNode*create(ListNode*head,ListNode*tail)
{
if(head==tail)return NULL;
ListNode*slow=head,*fast=head;
while(fast!=tail&&fast->next!=tail)slow=slow->next,fast=fast->next->next;
TreeNode*root=new TreeNode(slow->val);
root->left=create(head,slow);
root->right=create(slow->next,tail);
return root;
}
};
网友评论