Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 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) {
TreeNode* root = ToBST(nums, 0, nums.size()-1);
return root;
}
TreeNode* ToBST(vector<int>& nums, int l, int r){
if(l<=r)
{
int mid = l+(r-l+1)/2;
TreeNode* temp = new TreeNode(nums[mid]);
temp->left = ToBST(nums, l, mid-1);
temp->right = ToBST(nums, mid+1, r);
return temp;
}
else return NULL;
}
};