mirror of
https://github.com/TheAlgorithms/C
synced 2025-04-22 05:06:12 +03:00
24 lines
618 B
C
24 lines
618 B
C
struct TreeNode *buildBST(struct ListNode *head, struct ListNode *tail)
|
|
{
|
|
if (head == tail)
|
|
return NULL;
|
|
struct ListNode *slow = head, *fast = head;
|
|
while (fast != tail && fast->next != tail)
|
|
{
|
|
fast = fast->next->next;
|
|
slow = slow->next;
|
|
}
|
|
struct TreeNode *node = malloc(sizeof(struct TreeNode));
|
|
node->val = slow->val;
|
|
node->left = buildBST(head, slow);
|
|
node->right = buildBST(slow->next, tail);
|
|
return node;
|
|
}
|
|
struct TreeNode *sortedListToBST(struct ListNode *head)
|
|
{
|
|
if (!head)
|
|
return NULL;
|
|
else
|
|
return buildBST(head, NULL);
|
|
}
|