-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path108&109
64 lines (63 loc) · 1.63 KB
/
108&109
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
/**
* 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* sortedArrayToBST(vector<int>& nums) {
return helper(nums,0,nums.size()-1);
}
TreeNode* helper(const vector<int>&nums,int start,int end){
auto sz=end-start;
if(sz<0)return nullptr;
else if(sz==0)return new TreeNode(nums[start]);
auto 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;
}
};
//109
/**
* 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) {
return helper(head,nullptr);
}
private:
TreeNode* helper(ListNode*head,ListNode*tail){
if(head==tail)return nullptr;
else if(head->next==tail)return new TreeNode(head->val);
auto slow=head,fast=head;
while(fast!=tail&&fast->next!=tail){
slow=slow->next;
fast=fast->next->next;
}
auto root=new TreeNode(slow->val);
root->left=helper(head,slow);
root->right=helper(slow->next,tail);
return root;
}
};