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;
}
网友评论