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);
}
posted @ 2019-01-12 15:38  INnoVation-V2  阅读(100)  评论(0编辑  收藏  举报