108. Convert Sorted Array to Binary Search Tree
题意:
生成二叉平衡树。
思路:递归
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* sortedArrayToBST(vector<int>& nums, int beg, int end) {//8ms
if (end < beg)
return NULL;
int mid = (beg + end) / 2;
TreeNode* p = new TreeNode(nums[mid]);
if (end == beg)
return p;
p->left = sortedArrayToBST(nums, beg, mid - 1);
p->right = sortedArrayToBST(nums, mid + 1, end);
return p;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.empty())
return NULL;
return sortedArrayToBST(nums, 0, nums.size() - 1);
}