13 lines concise and easy understand c++ solution


  • 6
    A
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head) {
            if(!head) return NULL;
            ListNode* fast = head, * slow = head, * pre = NULL;
            while(fast && fast->next){
                fast = fast->next->next;
                pre = slow;
                slow = slow->next;
            }
            TreeNode* root = new TreeNode(slow->val);
            if(pre != NULL) pre->next = NULL;
            else head = 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.