题目描述
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
比较简单的二叉树题,数组转换成平衡二叉搜索树
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num)
{
return ArrayToBST(num,0,num.size());
}
TreeNode *ArrayToBST(vector<int> &num,int begin,int end)
{
if(begin >= end)
return nullptr;
int middle = (end+begin)>>1;
TreeNode *root = new TreeNode(num[middle]);
root->left = ArrayToBST(num,begin,middle);
root->right = ArrayToBST(num,middle+1,end);
return root;
}
};