思路:对于当前数组,去元素位置的中位数作为根节点,左右两端的元素分别构造子树,就能构造一颗平衡二叉树。
code:
class Solution {
public:
TreeNode * buildBST(vector<int>::iterator beginIt, int num){
vector<int>::iterator it = beginIt + num/2;
TreeNode *root = new TreeNode(*it);
if(it > beginIt)
root->left = buildBST(beginIt,num/2);
if(it < beginIt + num - 1)
root->right = buildBST(it+1,num - num/2 - 1);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
TreeNode * root;
if(num.size()>0)
return buildBST(num.begin(),num.size());
}
};