-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path109.有序链表转换二叉搜索树.cpp
69 lines (67 loc) · 1.91 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
/*
* @lc app=leetcode.cn id=109 lang=cpp
*
* [109] 有序链表转换二叉搜索树
*/
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
// 69 24;
// 被平衡树吓到了,其实不复杂
TreeNode* sortedListToBST(ListNode* head) {
vector<int> v;
ListNode* p = head;
while(p){
v.push_back(p->val);
p = p->next;
}
return recur(v, 0, v.size()-1);
}
TreeNode* recur(vector<int>& v, int begin, int end){
if(begin > end){
return nullptr;
}
int mid = (end + begin) / 2;
TreeNode *root = new TreeNode(v[mid]);
root->left = recur(v, begin, mid-1);
root->right = recur(v, mid+1, end);
return root;
}
};
// @lc code=end