Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:
本题给定一个排序好的数组,要求构造一棵二叉树。由于二叉树中序遍历的结果就是一个升序数组,因此逆向思维,采用分治发,递归构造二叉树。
具体代码如下:
class Solution {
public:
TreeNode* sortedArrayToBSTHelper(vector<int>& nums, int begin, int end)
{
if(begin > end) return NULL;
int mid = (begin + end)/2;
TreeNode * root = new TreeNode(nums[mid]);
root->left = sortedArrayToBSTHelper(nums,begin,mid-1);
root->right = sortedArrayToBSTHelper(nums,mid+1,end);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size() == 0) return NULL;
return sortedArrayToBSTHelper(nums, 0, nums.size()-1);
}
};