题目:给定一个有序整数数组,元素各不相同且按升序排列,编写一个算法,创建一棵高度最小的二叉搜索树。
example:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
解答:
/**
* 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;
TreeNode* root = insertTreeNode(nums,0,nums.size()-1);
return root;
}
TreeNode* insertTreeNode(vector<int>& nums,int left,int right)
{
if(left > right) //递归的终止条件
{
return NULL;
}
int mid = (left + right) /2;
TreeNode* node = new TreeNode(nums[mid]);
node->left = insertTreeNode(nums,left,mid - 1);
node->right = insertTreeNode(nums,mid + 1,right);
return node;
}
};