forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
109.cpp
78 lines (62 loc) · 1.54 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>
using namespace std;
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) {
if (head == NULL) return NULL;
ListNode *fast, *slow, *prev;
fast = slow = head;
prev = NULL;
while (fast) {
fast = fast->next;
if (!fast) break;
fast = fast->next;
prev = slow;
slow = slow->next;
}
if (slow == NULL) return NULL;
if (prev) prev->next = NULL;
TreeNode *node = new TreeNode(slow->val);
node->left = sortedListToBST(slow == head ? NULL : head);
node->right = sortedListToBST(slow->next);
return node;
}
void preOrderTraversal(TreeNode *root) {
if (root == NULL) return;
printf("%d ", root->val);
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
};
int main() {
ListNode *head = new ListNode(1);
ListNode *p = head;
for (int i = 2; i <= 7; i++) {
p->next = new ListNode(i);
p = p->next;
}
p->next = NULL;
p = head;
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
Solution s;
TreeNode *root = s.sortedListToBST(head);
s.preOrderTraversal(root);
printf("\n");
return 0;
}