-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path109.cpp
52 lines (44 loc) · 1.13 KB
/
109.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <cmath>
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if (!head)
return NULL;
ListNode *node = head;
int start = 0;
int end = 0;
while (node->next) {
++end;
node = node->next;
}
return buildBST(start, end, &head);
}
TreeNode* buildBST(int start, int end, ListNode **headRef) {
if (start > end)
return NULL;
TreeNode *node = new TreeNode(0);
int mid = (start + end) / 2;
node->left = buildBST(start, mid - 1, headRef);
node->val = (*headRef)->val;
*headRef = (*headRef)->next;
node->right = buildBST(mid + 1, end, headRef);
return node;
}
};