1、题目:点击打开链接
2、给定一个数组,将其转换为一个平衡二叉查找树
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
3、代码16ms:
/**
* 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) {
if(nums.empty())
return NULL;
int len=nums.size();
int mid=(len-1)/2;
TreeNode* treeNode=NULL;
Bst(treeNode,nums,0,len-1);
return treeNode;
}
void Bst(TreeNode* &treeNode,vector<int>& nums,int left,int right){
int mid=(left+right)/2;
//cout<<"l="<<left<<" r="<<right<<endl;
treeNode=new TreeNode(nums[mid]);
if(left<=mid-1)
Bst(treeNode->left,nums,left,mid-1);
if(mid+1<=right)
Bst(treeNode->right,nums,mid+1,right);
}
};