108. Convert Sorted Array to Bin
2017-01-07 本文已影响0人
juexin
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
class Solution {
public:
TreeNode* createTree(vector<int>& nums,int left,int right)
{
if(left>right)
return NULL;
int mid = (left+right)>>1;
TreeNode* leftNode = createTree(nums,left,mid-1);
TreeNode* rightNode = createTree(nums,mid+1,right);
TreeNode* node = new TreeNode(nums[mid]);
node->left = leftNode;
node->right = rightNode;
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return createTree(nums,0,nums.size()-1);
}
};