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.
给定一个数组,其中元素按升序排序,将其转换为高度平衡的BST。
对于这个问题,高度平衡的二叉树被定义为二叉树,其中每个节点的两个子树的深度从不相差超过1。
2,题目思路
对于这道题,给定一个数组,将其转化为一个高度平衡的BST。
当我们给定一个排序好的数组后,根据二叉搜索树的特点,很容易将其转换为一个BST,而且每一个数字都可以作为这棵树的根节点,只不过树的形状不同罢了。
如果我们想让构建的树是一颗高度平衡的二叉树,那么,我们就要保证左右子树的高度之差不能超过1,即两颗子树的节点的个数是一样(或者节点数不超过1),而且这个要求是递归的。
因此,在构建这个BST时,我们每次都取当前数组的中间节点作为根节点,并将左区间内的节点所构成的二叉树作为当前节点的左子树,右区间内的的节点所构成的二叉树作为当前节点的右子树,递归地进行寻找即可。
3,代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int n = nums.size();
if(n == 0)
return nullptr;
return BSTHelper(nums, 0, n-1);
}
TreeNode* BSTHelper(vector<int>& nums, int left, int right){
if(left > right)
return nullptr;
int mid = left + (right - left)/2;
TreeNode *root = new TreeNode(nums[mid]);
root->left = BSTHelper(nums, left, mid-1);
root->right= BSTHelper(nums, mid+1,right);
return root;
}
};