码迷,mamicode.com
首页 > 其他好文 > 详细

【Lintcode】106.Convert Sorted List to Balanced BST

时间:2017-05-13 16:54:50      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:while   tno   order   题解   sort   amp   int   solution   ==   

题目:

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;
    }

};

 

【Lintcode】106.Convert Sorted List to Balanced BST

标签:while   tno   order   题解   sort   amp   int   solution   ==   

原文地址:http://www.cnblogs.com/Atanisi/p/6849156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!