从head指针开始,直到fast
指针为null
或者fast->next==null
为止,找到这个链表的中间节点。利用这个中间节点构造出该子树的根节点,再将中间节点的左边的节点的next
指针置空,目的是不使用额外参数控制该段的边界。递归地初始化左子树,以及右子树。
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
// 处理空节点和单节点的情况
if (head == nullptr) return nullptr;
if (head->next == nullptr) return new TreeNode(head->val);
// 寻找中间节点
ListNode *slow = head, *fast = head->next->next;
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
}
// 分别处理左右节点,并把中间的节点提取出来
TreeNode *node = new TreeNode(slow->next->val);
node->right = sortedListToBST(slow->next->next);
slow->next = nullptr;
node->left = sortedListToBST(head);
return node;
}
};