将有序数组当做一个二叉搜索树的中序遍历,每次从中间分开,以保证子树平衡,递归的写出算法。
时间复杂度:O(N)
C++代码:
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.empty())
return nullptr;
int mid = nums.size() >> 1;
TreeNode* root = new TreeNode(nums[mid]);
arrayToBST(nums, 0, mid - 1, root, 0);
arrayToBST(nums, mid + 1, nums.size() - 1, root, 1);
return root;
}
void arrayToBST(vector<int>& num, int st, int en, TreeNode* root, int dir)
{
if (st > en)
return;
int mid = (st + en) >> 1;
TreeNode* temp = new TreeNode(num[mid]);
if (dir)
root->right = temp;
else
root->left = temp;
if (st != en)
{
if (dir)
{
arrayToBST(num, st, mid - 1, root->right, 0);
arrayToBST(num, mid + 1, en, root->right, 1);
}
else
{
arrayToBST(num, st, mid - 1, root->left, 0);
arrayToBST(num, mid + 1, en, root->left, 1);
}
}
}
};