把一个排序的数组建成一个平衡的BST。既然是平衡的,就想到从中间位置开始建立根节点,然后左子树根节点又是左边一半的中间位置,右子树根节点又是右边一半的中间位置。很明显用递归可以解决。我的代码:
/**
* 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.size() == 0)
return NULL;
return getBST(nums, 0, nums.size()-1);
}
TreeNode* getBST(vector<int>& nums, int start, int end)
{
if(start > end)
{
return NULL;
}
else
{
int mid = (start + end) / 2;
TreeNode* newtree = new TreeNode(nums[mid]);
newtree->left = getBST(nums, start, mid - 1);
newtree->right = getBST(nums, mid + 1, end);
return newtree;
}
}
};