题目描述
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.
Example1:
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
解题思路
- 划分迭代
- 有一个疑问,求中点的时候 mid = (begin + end) / 2 // 这个也能通过,但是 效率没有第二个好
- 而正确的求中点的方式 应该为 mid = begin + (end - begin) / 2
- 注意begin = end 相等的时候,直接返回new出来的新节点即可
/**
* 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 nullptr;
}
return funHelper(nums, 0, nums.size() - 1);
}
// 递归需要有个截止条件
TreeNode* funHelper(vector<int>& nums, int begin, int end){
if(begin > end){
return nullptr;
}
int mid = (begin + end) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root -> left = funHelper(nums, begin, mid - 1);
root -> right = funHelper(nums, mid + 1, end);
return root;
}
};
/**
* 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;
}
TreeNode* root = fun_helper(nums, 0, nums.size() - 1);
return root;
}
TreeNode* fun_helper(vector<int>& nums, int begin, int end){
if(begin > end){
return NULL;
}else if(begin == end){
return new TreeNode(nums[begin]);
}
int mid = (begin + end) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root -> left = fun_helper(nums, begin, mid - 1);
root -> right = fun_helper(nums, mid + 1, end);
return root;
}
};