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;
}
};
本文介绍了一种将已排序的数组转换为高度平衡的二叉搜索树的方法。平衡二叉树定义为任意节点的左右子树深度之差不超过1。示例中给出了一种可能的解决方案,将数组[-10,-3,0,5,9]转化为平衡二叉搜索树。文章详细解释了使用递归策略选择中间元素作为根节点的过程。
1361

被折叠的 条评论
为什么被折叠?



