My recursive cpp code


  • 0
    C
    class Solution {
    public:
        ListNode* findCenter(ListNode* head, ListNode* tail)
        {
            if(head==tail || head->next==tail) return head;
            
            ListNode* slow = head;
            ListNode* fast = head->next->next;
            
            while(fast != tail)
            {
                slow = slow->next;
                fast = fast->next;
                if(fast != tail) fast = fast->next;
            }
            
            return slow;
        }
        
        TreeNode* helper(ListNode* head, ListNode*tail)
        {
            if(head == tail) return NULL;
            if(head->next == tail) return new TreeNode(head->val);
            
            ListNode* center = findCenter(head, tail);
            TreeNode* t1 = helper(head, center);
            TreeNode* t2 = helper(center->next, tail);
            
            TreeNode* tree = new TreeNode(center->val);
            tree->left = t1;
            tree->right = t2;
            
            return tree;
        }
    
        TreeNode* sortedListToBST(ListNode* head) 
        {
            return helper(head, NULL);
        }
    };

Log in to reply
 

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