Share my solution with recursive search


  • 0
    M
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head) {
            int len = 0;
            ListNode* p = head;
            while (p) {
                p = p->next;
                len++;
            }
            return build(head, 0, len - 1);
        }
    
        TreeNode* build(ListNode*& head, int start, int end) {
            if (start > end)
                return nullptr;
            int mid = (start + end) >> 1;
            TreeNode* lchild = build(head, start, mid - 1);
            TreeNode* root = new TreeNode(head->val);
            root->left = lchild;
            head = head->next;
            root->right = build(head, mid + 1, end);
            return root;
        }
    };
    

Log in to reply
 

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