109 有序链表转二叉搜索树

TreeNode *BST(ListNode *begin, ListNode *end) {
    if (begin == end)
        return nullptr;
    ListNode *fast = begin, *slow = begin;
    while (fast->next != end) {
        fast = fast->next;
        if (fast->next == end)
            break;
        fast = fast->next;
        slow = slow->next;
    }
    auto *mid = new TreeNode(slow->val);
    mid->left = BST(begin, slow);
    mid->right = BST(slow->next, end);
    return mid;
};

TreeNode *sortedListToBST(ListNode *head) {
    if (head == nullptr)
        return nullptr;
    else if (head->next == nullptr)
        return new TreeNode(head->val);
    return BST(head, nullptr);
}
原文地址:https://www.cnblogs.com/INnoVationv2/p/10259966.html