How about like this?


  • 8
    A
    TreeNode *sortedListToBST(ListNode *head) {
        if(head == NULL) return NULL;
        if(head->next == NULL) return new TreeNode(head->val);
        ListNode *step1 = head;
        ListNode *step2 = head->next;
        while(step2->next != NULL && step2->next->next != NULL){
            step1 = step1->next;
            step2 = step2->next->next;
        }
        TreeNode *root  = new TreeNode(step1->next->val);
        ListNode *head2 = step1->next->next;
        delete step1->next;
        step1->next = NULL;
        root->left = sortedListToBST(head);
        root->right = sortedListToBST(head2);
        return root;
    }

Log in to reply
 

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