給一個排序數(shù)組(從小到大)箱玷,將其轉(zhuǎn)換為一棵高度最小的排序二叉樹稼稿。
/**
* 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 A: A sorted (increasing order) array
* @return: A tree node
*/
TreeNode * bst(vector<int > & A ,int beg,int end){
if(beg>end){
return NULL;
}
if(beg==end){
TreeNode * node1=new TreeNode(A[end]);
return node1;
}
if(beg==end-1){
TreeNode * node2=new TreeNode(A[beg]);
node2->right=new TreeNode(A[end]);
return node2;
}
int mid=(beg+end)/2;
TreeNode * node =new TreeNode(A[mid]);
node->left=bst(A,beg,mid-1);
node->right=bst(A,mid+1,end);
return node;
}
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
if(A.size()==0){
return NULL;
}
TreeNode * bsttree;
if(A.size()==1){
bsttree =new TreeNode(A[0]);
return bsttree;
}
int mid=(0+A.size()-1)/2;
bsttree=new TreeNode(A[mid]);
bsttree->left=bst(A,0,mid-1);
bsttree->right=bst(A,mid+1,A.size()-1);
return bsttree;
}
};