Day35: [LeetCode简单] 108. 将有序数组转换为二叉搜索树
程序员文章站
2022-03-15 20:35:53
...
Day35: [LeetCode简单] 108. 将有序数组转换为二叉搜索树
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
代码:
dirty code凑合看吧
/**
* 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:
int Len;
TreeNode* f(vector<int>& nums,int left,int right){
if(left>right) return NULL;
int mid=(left+right)/2;
TreeNode* p=new TreeNode(nums[mid]);
p->left=f(nums,left,mid-1);
p->right=f(nums,mid+1,right);
return p;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
Len=nums.size();
if(Len==0) return NULL;
return f(nums,0,Len-1);
}
};