-
Notifications
You must be signed in to change notification settings - Fork 33
/
convert-sorted-list-to-binary-search-tree_2(AC).cpp
61 lines (59 loc) · 1.32 KB
/
convert-sorted-list-to-binary-search-tree_2(AC).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
/**
* 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 = head;
vector<int> A;
while (p != NULL) {
A.push_back(p->val);
p = p->next;
}
return sortedArrayToBST(A);
}
TreeNode *sortedArrayToBST(vector<int> &A) {
if (A.empty()) {
return NULL;
}
return convert(A, 0, A.size() - 1);
}
private:
TreeNode* convert(vector<int> &a, int ll, int rr) {
int mm = (ll + rr) / 2;
TreeNode* root = new TreeNode(a[mm]);
if (ll < mm) {
root->left = convert(a, ll, mm - 1);
}
if (rr > mm) {
root->right = convert(a, mm + 1, rr);
}
return root;
}
};