forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.c
40 lines (38 loc) · 981 Bytes
/
Solution.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct ListNode* find(struct ListNode* start, struct ListNode* end) {
struct ListNode* fast = start;
struct ListNode* slow = start;
while (fast != end && fast->next != end) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
struct TreeNode* bulid(struct ListNode* start, struct ListNode* end) {
if (start == end) {
return NULL;
}
struct ListNode* node = find(start, end);
struct TreeNode* ans = malloc(sizeof(struct TreeNode));
ans->val = node->val;
ans->left = bulid(start, node);
ans->right = bulid(node->next, end);
return ans;
}
struct TreeNode* sortedListToBST(struct ListNode* head) {
return bulid(head, NULL);
}