forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.h
35 lines (32 loc) · 879 Bytes
/
solution.h
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
#include <cstddef>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
auto n = [](ListNode *p){
int count{0};
for ( ; p; p=p->next, ++count);
return count;
}(head);
return sortedListToBST(&head, n);
}
TreeNode *sortedListToBST(ListNode **head_ref, int n) {
if (n<1) return NULL;
TreeNode *left = sortedListToBST(head_ref, n/2);
TreeNode *root = new TreeNode((*head_ref)->val);
root->left = left;
*head_ref = (*head_ref)->next;
root->right = sortedListToBST(head_ref, n-n/2-1);
return root;
}
};