-
Notifications
You must be signed in to change notification settings - Fork 0
/
Convert Sorted List to Binary Search Tree.cpp
58 lines (47 loc) · 1.31 KB
/
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
/**
* 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) {
if (head == NULL)
return NULL;
ListNode* p = head, *pNext = p->next;
vector<int> myNum;
while (p != NULL) {
myNum.push_back(p->val);
p = pNext;
if (pNext != NULL)
pNext = pNext->next;
}
return sortedArrayToBST(myNum);
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.size() == 0)
return NULL;
return generateBST(nums, 0, nums.size()-1);
}
TreeNode* generateBST(vector<int> & nums, int start, int end) {
if (start > end)
return NULL;
int mid = (start + end)/2;
TreeNode *p = new TreeNode(nums[mid]);
p->left = generateBST(nums, start, mid - 1);
p->right = generateBST(nums, mid + 1, end);
return p;
}
};