1 题目
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
2 尝试解
2.1 分析
采用递归思路,如[1,2,3,4,5],以3为根节点,左子树为[1,2],右子树[4,5],实现递归。递归需要四个参数,原始数组,待建立子树对应数组中的起点和终点,子树的根节点。
2.2 代码
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = NULL;
if(nums.size() == 0) return root;
root = new TreeNode(0);
BuildTree(nums,0,nums.size()-1,root);
return root;
}
void BuildTree(vector<int>& nums, int start,int end,TreeNode* root){
if(start == end) {
root->val = nums[start];
}
else{
int mid = (start + end)/2;
root->val = nums[mid];
if(mid < end){
root->right = new TreeNode(0);
BuildTree(nums,mid+1,end,root->right);
}
if(start < mid){
root->left = new TreeNode(0);
BuildTree(nums,start,mid-1,root->left);
}
}
}
};
3 标准解
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
if(num.size() == 0) return NULL;
if(num.size() == 1)
{
return new TreeNode(num[0]);
}
int middle = num.size()/2;
TreeNode* root = new TreeNode(num[middle]);
vector<int> leftInts(num.begin(), num.begin()+middle);
vector<int> rightInts(num.begin()+middle+1, num.end());
root->left = sortedArrayToBST(leftInts);
root->right = sortedArrayToBST(rightInts);
return root;
}
};