@LIUHUAN
2019-12-29T17:48:19.000000Z
字数 1383
阅读 824
algorithm
/**
* 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) {
int n = nums.size();
return func(nums,0,n-1);
}
TreeNode* func(vector<int> &nums,int i ,int j) {
if(i > j )
return nullptr;
if(i == j ) {
return new TreeNode(nums[i]);
}
int mid = (i + j) / 2;
TreeNode *root = new TreeNode(nums[mid]);
root->left = func(nums,i,mid-1);
root->right = func(nums,mid+1,j);
return root;
}
};
/**
* 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) {
vector<ListNode*> vec;
while(head) {
vec.push_back(head);
head = head->next;
}
int n = vec.size();
return func(vec,0,n-1);
}
TreeNode* func(vector<ListNode*> &nums,int i ,int j) {
if(i > j )
return nullptr;
if(i == j ) {
return new TreeNode(nums[i]->val);
}
int mid = (i + j) / 2;
TreeNode *root = new TreeNode(nums[mid]->val);
root->left = func(nums,i,mid-1);
root->right = func(nums,mid+1,j);
return root;
}
};