Simple yet efficient solution in cpp


  • 0
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head) {
            if(!head) return NULL;
            ListNode *slow=head, *fast=head;
            ListNode *pre = NULL;
            while(fast && fast->next)
            {
                pre = slow;
                slow = slow->next;
                fast = fast->next->next;
            }
            int val = slow->val;
            TreeNode *root = new TreeNode(val);
            if(!pre) return root;
            pre->next = NULL;
            root->left = sortedListToBST(head);
            root->right = sortedListToBST(slow->next);
            return root;
        }
    };

Log in to reply
 

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