C++ recursive solution.


  • 0
    C
    TreeNode* sortedListToBST(ListNode* head) {
        if (head == nullptr)
            return NULL;
        if (head->next == NULL) {
            TreeNode *res = new TreeNode(head->val);
            return res;
        }
        ListNode *fast = head->next->next, *slow = head;
        while (fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode *p = slow->next;
        TreeNode *res = new TreeNode(p->val);
        slow->next = NULL;   //take care here
        res->left = sortedListToBST(head);
        res->right = sortedListToBST(p->next);
        return res;
    }

  • 0
    S

    The original List would be broken...


Log in to reply
 

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