您的位置:首页 > 其它

[leetcode]Convert Sorted Array to Binary Search Tree

2015-11-02 23:09 375 查看
Convert Sorted Array to Binary Search Tree My Submissions Question

Total Accepted: 57734 Total Submissions: 165322 Difficulty: Medium

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Subscribe to see which companies asked this question

/**
* 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 len = nums.size();
if(!len)    return nullptr;
int l = 0;
int r = len - 1;
int mid = l + (r - l) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = func(nums,l,mid - 1);
root->right = func(nums,mid + 1,r);
return root;
}
TreeNode* func(const vector<int>& nums,int l,int r){
if(l > r)   return nullptr;
int mid = l + (r - l) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = func(nums,l,mid - 1);
root->right = func(nums,mid + 1,r);
return root;
}
};


递归解决,一遍过的感觉不要太爽啊 哈哈~

暂时忽略函数命名。。。不要让想函数名扰乱我的思路:)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: