forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert-sorted-list-to-binary-search-tree(AC).cpp
More file actions
66 lines (65 loc) · 1.45 KB
/
convert-sorted-list-to-binary-search-tree(AC).cpp
File metadata and controls
66 lines (65 loc) · 1.45 KB
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
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
TreeNode *sortedListToBST(ListNode *head) {
if (head == NULL) {
return NULL;
}
ListNode *p;
int len = 0;
p = head;
while (p != NULL) {
p = p->next;
++len;
}
return convert(head, len);
}
private:
TreeNode *convert(ListNode *head, int len) {
if (len == 0) {
return NULL;
}
if (len == 1) {
return new TreeNode(head->val);
}
if (len == 2) {
TreeNode *h = new TreeNode(head->val);
h->right = new TreeNode(head->next->val);
return h;
}
int i;
ListNode *p = head;
for (i = 1; i <= (len - 1) / 2; ++i) {
p = p->next;
}
TreeNode *r = new TreeNode(p->val);
r->left = convert(head, (len - 1) / 2);
r->right = convert(p->next, len / 2);
return r;
}
};