给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
注意事项
There may exist multiple valid solutions, return any of them.
样例
给出数组 [1,2,3,4,5,6,7]
, 返回
4
/ \
2 6
/ \ / \
1 3 5 7
我的解题思路是:由已给样例我们可以看出数组的中间一个数据是作为根节点存在的,而中间的左面全部都在树的左子树上,右面的全部都在树的右子树上。根据这个思路我们可以将数组划分为两部分,分别给左子树和右子树,然后按照这个思路一直递归下去。就可以完美的解决这个问题了。
/**
* 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 *creat(vector<int> &A,int start,int end)
{
if(start>end)return NULL;
int mid=(start+end)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=creat(A,start,mid-1);
root->right=creat(A,mid+1,end);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
int n=A.size();
if(n==0)
return NULL;
int mid=(n)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=creat(A,0,mid-1);
root->right=creat(A,mid+1,n-1);
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 *creat(vector<int> &A,int start,int end)
{
if(start>end)return NULL;
int mid=(start+end)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=creat(A,start,mid-1);
root->right=creat(A,mid+1,end);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
int n=A.size();
if(n==0)
return NULL;
int mid=(n)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=creat(A,0,mid-1);
root->right=creat(A,mid+1,n-1);
return root;
}
};