Share my cpp solution


  • 0
    O
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head) {
            if (head == NULL) return NULL;
            TreeNode *ans;
            if (head->next == NULL) {
                ans = new TreeNode(head->val);
                return ans;
            }
            ListNode dummy(0);
            dummy.next = head;
            auto slow = &dummy, fast = head;
            while (fast != NULL && fast->next != NULL) {
                fast = fast->next->next;
                slow = slow->next;
            }
            ListNode *middle = slow->next;
            slow->next = NULL;
            ans = new TreeNode(middle->val);
            ans->left = sortedListToBST(head);
            ans->right = sortedListToBST(middle->next);
            return ans;
        }
    };

Log in to reply
 

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