算法
(树、DFS)
每次选择一个区间的中点作为当前区间的根,然后对左右子树依次构造。
C++ 代码
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return helper(nums, 0, nums.size() - 1);
}
TreeNode *helper(vector<int> &nums, int left, int right) {
if (left > right) { return NULL; }
int aMid = (left + right) / 2;
TreeNode *aRoot = new TreeNode(nums[aMid]);
aRoot->left = helper(nums, left, aMid - 1);
aRoot->right = helper(nums, aMid + 1, right);
return aRoot;
}
};