给定一个数组,其中元素按升序排序,将其转换为高度平衡的BST。对于这个问题,高度平衡的二叉树被定义为二叉树,其中每个节点的两个子树的深度从不相差超过1。
样例
样例 1:
输入: [-10,-3,0,5,9],
输出: [0,-3,9,-10,#,5],
解释:
针对该数组的其中一个解为 [0,-3,9,-10,null,5], 其对应的平衡BST树如下:
0
/ \
-3 9
/ /
-10 5
样例 2:
输入: [1,3]
输出: [3,1]
解释:
针对该数组的其中一个解为 [3,1], 其对应的平衡BST树如下:
3
/
1
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param nums: the sorted array
* @return: the root of the tree
*/
TreeNode * convertSortedArraytoBinarySearchTree(vector<int> &A) {
// Write your code here.
if(A.empty()) return NULL;
TreeNode*newroot=builtree(A,0,A.size()-1);
return newroot;
}
TreeNode*builtree(vector<int>&A,int low,int high)
{
if(low>high) return NULL;
int mid=low+(high-low)/2;
TreeNode* newroot=new TreeNode(A[mid]);
newroot->left=builtree(A,low,mid-1);
newroot->right=builtree(A,mid+1,high);
return newroot;
}
};