-
Notifications
You must be signed in to change notification settings - Fork 7
/
109.cpp
42 lines (39 loc) · 1011 Bytes
/
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
/**
* 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) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
ListNode* p = head;
int count = 0;
while(p) {
count++;
p = p->next;
}
return sortedListToBSTCore(count,&head);
}
private:
TreeNode* sortedListToBSTCore(int count,ListNode** curr){
if(count <= 0) return NULL;
TreeNode *root = new TreeNode(0);
root->left = sortedListToBSTCore(count / 2,curr);
root->val = (*curr)->val;
(*curr) = (*curr)->next;
root->right = sortedListToBSTCore(count - count / 2 - 1,curr);
return root;
}
};