/*这道题与Convert Sorted Array to Binary Search Tree很类似,可以采用
相同的方法解题,但是链表不支持随机访问,所以每次都需要查找链表的中间节点。
同时,还有一个需要注意的地方:需要将输入的链表复制出来处理,否则会报错。*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head == nullptr) return nullptr;
//复制原来的链表到新的链表中,因为不能改变原来的链表。
//(试过不把原来的链表复制出来,但提交时失败的。)
ListNode node(-1), *tail(&node);
while(head != nullptr){
tail->next = new ListNode(head->val);
head = head->next;
tail = tail->next;
}
head = node.next;
ListNode *fast(head), *slow(head), *pre_slow(nullptr);
while(fast->next != nullptr && fast->next->next != nullptr){
fast = fast->next->next;
pre_slow = slow;
slow = slow->next;
}
TreeNode *root = new TreeNode(slow->val);
ListNode *p(slow->next);
delete slow;
if(pre_slow != nullptr){
pre_slow->next = nullptr;
root->left = sortedListToBST(head);
}
root->right = sortedListToBST(p);
return root;
}
};