-
Notifications
You must be signed in to change notification settings - Fork 0
/
sortedSinglyListToBST.c
83 lines (71 loc) · 1.75 KB
/
sortedSinglyListToBST.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <stdlib.h>
typedef struct elementT {
struct elementT *next;
struct elementT *left;
struct elementT *right;
int data;
} element;
int countElements(element *h) {
int sum = 0;
while(h) {
sum++;
h = h->next;
}
return sum;
}
void printList(element *h) {
while(h) {
printf("%d ", h->data);
h = h->next;
}
printf("\n");
}
element *makeNode(int d) {
element *ele = (element *)malloc(sizeof(element));
ele->data = d;
return ele;
}
element *sortedSinglyListToBST(element *head) {
if(!head)
return NULL;
if(!(head->next))
return head;
element *slow = head, *fast = head->next, *pre = NULL;
while(fast && fast->next) {
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
element *r = slow;
if(pre != NULL)
pre->next = NULL;
//printList(head);
if(slow != head)
r->left = sortedSinglyListToBST(head);
r->right = sortedSinglyListToBST(slow->next);
//printf("%d\n", slow->data);
return r;
}
element *sortedSinglyListToBSTRecSub(element **ele, int n) {
if(n <= 0)
return NULL;
element *left = sortedSinglyListToBSTRecSub(ele, n/2);
element *root = makeNode((*ele)->data);
root->left = left;
*ele = (*ele)->next;
root->right = sortedSinglyListToBSTRecSub(ele, n - n / 2 - 1);
return root;
}
element *sortedSinglyListToBSTRec(element *head) {
int n = countElements(head);
return sortedSinglyListToBSTRecSub(&head, n);
}
main()
{
element *head = makeNode(2);
head->next = makeNode(4);
head->next->next = makeNode(5);
head->next->next->next = makeNode(6);
element *root = sortedSinglyListToBSTRec(head);
}