C++ solution , accepted


  • 0
    F

    class Solution {
    public:
    TreeNode* sortedListToBST(ListNode* head) {
    if(head == NULL)//异常情况返回
    {
    return NULL;
    }
    ListNode* slow = getMid(head);//得到中间值
    if(slow->next == NULL)
    {
    TreeNode* root = new TreeNode(slow->val);
    return root;
    }
    ListNode* sedhead = slow->next;
    slow->next = NULL;//分为2个链表
    TreeNode* root = new TreeNode(sedhead->val);
    root->left = sortedListToBST(head);
    if(sedhead->next != NULL)
    {
    root->right = sortedListToBST(sedhead->next);
    }
    return root;
    }

    ListNode* getMid(ListNode* head)
    {
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* pre = head;
        if(head == NULL)
        {
            return NULL;
        }
        while(fast->next != NULL && fast->next->next != NULL)
        {
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        return pre;
    }
    

    };>! Spoiler


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.