lintcode——把排序陣列轉換為高度最小的二叉搜尋樹
阿新 • • 發佈:2019-02-20
/**
* 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 *ToBST(vector<int> &T,int a,int c) //需要呼叫的函式,開始轉換
{
if(a>c)
return NULL;
else{
int b=(a+c)/2;
TreeNode *root=new TreeNode(T[b]);
root->left=ToBST(T,a,b-1);
root->right=ToBST(T,b+1,c);
return root;
}
}
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
if(A.empty())
return NULL;
else
{ int begin=0,end=A.size()-1,mid=(begin+end)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=ToBST(A,begin,mid-1); //呼叫函式
root->right=ToBST(A,mid+1,end); //呼叫函式
return root;
}
}
};
* 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 *ToBST(vector<int> &T,int a,int c) //需要呼叫的函式,開始轉換
{
if(a>c)
return NULL;
else{
int b=(a+c)/2;
TreeNode *root=new TreeNode(T[b]);
root->left=ToBST(T,a,b-1);
root->right=ToBST(T,b+1,c);
return root;
}
}
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
if(A.empty())
return NULL;
else
{ int begin=0,end=A.size()-1,mid=(begin+end)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=ToBST(A,begin,mid-1); //呼叫函式
root->right=ToBST(A,mid+1,end); //呼叫函式
return root;
}
}
};