zoukankan      html  css  js  c++  java
  • 【Lintcode】106.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;
        }
    
    };
  • 相关阅读:
    信号灯的典型应用
    字符串过滤
    做一些学习的事情一定要坚持下去
    昨天的你造就今天的你,今天的你准备怎么造就明天的你呢?
    vue中计算属性,方法,侦听器
    vue模板语法
    Vue实例的生命周期钩子
    VUE实例
    简单的组件间传值
    前端组件化
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6849156.html
Copyright © 2011-2022 走看看