my answer with c++


  • 0
    L

    class Solution {
    public:

    TreeNode* sortedListToBST(ListNode* head) {
        if (head == NULL) return NULL;
        int len = 0;
        ListNode *p = head;
        while(p){
            len++; 
            p = p->next;
        }
        return createTree(head, 0, len-1);
    }
    
    TreeNode *createTree(ListNode *node, int left, int right){
        if (left > right) return NULL;
        ListNode *p = node;
        int mid = (left + right + 1)/2;
        for (int i = left; i < mid; i++){
            p = p->next;
        }
        TreeNode *root = new TreeNode(p->val);
        root->left = createTree(node, left, mid-1);
        root->right = createTree(p->next, mid+1, right);
        return root;
    }
    

    };


Log in to reply
 

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