-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path109. Convert Sorted List to Binary Search Tree.cpp
123 lines (87 loc) · 2.23 KB
/
109. Convert Sorted List to Binary Search Tree.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/**
* 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 {
TreeNode *helper(ListNode *head, ListNode *last) {
if (! head)
return nullptr;
if (head && last && head == last)
return nullptr;
ListNode *slow = head;
ListNode *fast = head;
while (fast != last && fast->next != last) {
slow = slow->next;
fast = fast->next->next;
}
TreeNode *root = new TreeNode (slow->val);
root->left = helper(head, slow);
root->right = helper(slow->next, last);
return root;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
if (!head)
return nullptr;
TreeNode *root = helper(head, nullptr);
return root;
}
};
--------------
/*
Cheat solution : Put everything in a vector & convert sorted array to a bst.
Likely won't be accepted by any interviewer
*/
/**
* 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 {
TreeNode *helper(vector<int> &nums, int start, int end) {
if (start > end)
return nullptr;
int mid = start + (end-start)/2;
TreeNode *root = new TreeNode (nums[mid]);
root->left = helper(nums, start, mid-1);
root->right = helper(nums, mid+1, end);
return root;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
if (!head)
return nullptr;
vector<int> nums;
while(head) {
nums.push_back(head->val);
head = head->next;
}
TreeNode *root = helper(nums, 0, nums.size()-1);
return root;
}
};