1. 题目
2. 方法一
2.1. 代码
代码核心是寻找有序链表中的中间位置,然后把它上一个节点切断后,再作为父节点
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head==NULL) return NULL;
if(head->next==NULL) return new TreeNode(head->val);
ListNode *slow=head,*last_slow=slow,*fast=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
last_slow=slow;
slow=slow->next;
}
last_slow->next=NULL;
TreeNode* root =new TreeNode(slow->val);
root->left=sortedListToBST(head);
root->right=sortedListToBST(slow->next);
return root;
}
};