首页 > 其他 > 详细

109 有序链表转二叉搜索树

时间:2019-01-12 15:51:02      阅读:215      评论:0      收藏:0      [点我收藏+]
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);
}

109 有序链表转二叉搜索树

原文:https://www.cnblogs.com/INnoVationv2/p/10259966.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!