Lintcode106.Convert Sorted List to Balanced BST

Posted Vincent丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lintcode106.Convert Sorted List to Balanced BST相关的知识,希望对你有一定的参考价值。

题目:

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Example
               2
1->2->3  =>   /              1   3

 

题解:

Solution 1 ()

class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        if (!head) return nullptr;
        
        return sortedListToBST(head, nullptr); 
    }
    TreeNode *sortedListToBST(ListNode* head, ListNode* tail) {
        if (head == tail) return nullptr;
        ListNode* mid = head, *tmp = head;
        
        while (tmp != tail && tmp->next != tail) {
            mid = mid->next;
            tmp = tmp->next->next;
        }
        TreeNode* root = new TreeNode(mid->val);
        root->left = sortedListToBST(head, mid);
        root->right = sortedListToBST(mid->next, tail);
        
        return root;
    }

};

Solution 2 ()

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if (head == nullptr)
            return nullptr;
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* prev = nullptr; 
        while (fast != nullptr && fast->next != nullptr)
        {
            fast = fast->next->next;
            prev =slow;
            slow = slow->next;
        }
        TreeNode* root = new TreeNode(slow->val);
        if (prev != nullptr)
            prev->next = nullptr;
        else
            head  = nullptr;
            
        root->left = sortedListToBST(head);
        root->right = sortedListToBST(slow->next);
        
        return root;
    }

};

 

以上是关于Lintcode106.Convert Sorted List to Balanced BST的主要内容,如果未能解决你的问题,请参考以下文章

Deseja sua sorte boa, Renato Augusto

lintcode:单词切分

LintCode Subtree

LintCode Longest Common Subsequence

lintcode: 旋转图像

Lintcode: Segment Tree Build