-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP109.cpp
63 lines (57 loc) · 1.46 KB
/
P109.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
#include "header.h"
#include <cstddef>
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
int n=0;
ListNode* p = head;
while (p) {
n++;
p=p->next;
}
TreeNode *root = makeTree(n);
inOrderSet(root,head);
return root;
}
void inOrderSet(TreeNode *t,ListNode* &p) {
if (!t) return;
inOrderSet(t->left,p);
t->val = p->val;
p = p->next;
inOrderSet(t->right,p);
}
TreeNode * makeTree(int n) {
if (n==0) return nullptr;
TreeNode **table = new TreeNode*[n];
for (int i=0;i<n;i++) {
table[i] = new TreeNode(0);
if (i>0) {
int f = ((i+1)>>1)-1;
if ((i+1) % 2 ==0)
table[f]->left = table[i];
else
table[f]->right = table[i];
}
}
TreeNode *root = table[0];
delete[] table;
return root;
}
};
void testTree(TreeNode *t) {
if (!t) return;
testTree(t->left);
cout<<t->val<<" ";
testTree(t->right);
}
int main(int argc, const char *argv[]) {
ListNode * p = new ListNode(1);
ListNode * r = p;
p->next = new ListNode(2); p=p->next;
p->next = new ListNode(3); p=p->next;
p->next = new ListNode(4); p=p->next;
p->next = new ListNode(5); p=p->next;
auto k = Solution().sortedListToBST(r);
testTree(k);
return 0;
}