美文网首页
109 Convert Sorted List to Binar

109 Convert Sorted List to Binar

作者: larrymusk | 来源:发表于2017-12-05 11:04 被阅读0次
    struct TreeNode* sortedListToBST(struct ListNode* head) {
    
        
        if(head == NULL)
            return NULL;
        if(head->next == NULL){
            struct TreeNode *root = calloc(1, sizeof(struct TreeNode));
            root->val = head->val;
            return root;
        }
        struct ListNode *fast, *slow, *prev;
        struct ListNode *dummy = calloc(1, sizeof(struct ListNode));
        dummy->next = head;
        prev = dummy;
        slow = fast = head;
        while(fast->next){
            fast = fast->next;
            if(fast->next)
                fast = fast->next;
            slow = slow->next;
            prev = prev->next;
        }
        //
     
        //slow is mid pointer
        struct TreeNode *root = calloc(1, sizeof(struct TreeNode));
        root->val = slow->val;
        root->right = sortedListToBST(slow->next);
        prev->next = NULL;
        root->left = sortedListToBST(dummy->next);
     
    
        free(dummy);
    
        return root;    
    }

    相关文章

      网友评论

          本文标题:109 Convert Sorted List to Binar

          本文链接:https://www.haomeiwen.com/subject/zxvqixtx.html