http://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int leftCnt(int total){
if(total==1) return 0;
int left=1;
while(1){
int right=total-1-left;
if(left==right) break;
if(left>right){
right=left/2;
left=min(left,total-1-right);
break;
}
left=left*2+1;
}
return left;
}
void makeNode(TreeNode* &root, vector<int> &num, int start, int end){
if(start==end){
root=new TreeNode(num[start]);
}
else if(start<end){
int left=leftCnt(end-start+1);
int right=end-start-left;
root=new TreeNode(num[start+left]);
makeNode(root->left,num,start,start+left-1);
if(right>0) makeNode(root->right,num,start+left+1,end);
}
else
root=NULL;
}
TreeNode* sortedArrayToBST(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode *root=NULL;
makeNode(root,num,0,num.size()-1);
return root;
}
};