-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert-sorted-list-to-balanced-bst.cpp
72 lines (58 loc) · 1.34 KB
/
convert-sorted-list-to-balanced-bst.cpp
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
/**
* 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 {
int count (ListNode *node) {
int c = 0;
while (node) {
node = node->next;
c++;
}
return c;
}
TreeNode* generate (int n) {
if (n == 0) return nullptr;
TreeNode *node = new TreeNode(-1);
node->left = generate(n/2);
node->right = generate(n-n/2-1);
return node;
}
ListNode* fill (ListNode *lnode, TreeNode *tnode) {
if (!lnode || !tnode) return lnode;
lnode = fill (lnode, tnode->left);
tnode->val = lnode->val;
lnode = lnode->next;
lnode = fill(lnode, tnode->right);
return lnode;
}
public:
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
TreeNode *sortedListToBST(ListNode *head) {
int c = count(head);
TreeNode *root = generate(c);
fill(head, root);
return root;
}
};