题目描述:
给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
注意事项
There may exist multiple valid solutions, return any of them.
您在真实的面试中是否遇到过这个题? Yes
样例
给出数组 [1,2,3,4,5,6,7], 返回
4
/ \
2 6
/ \ / \
1 3 5 7
ac代码:
/**
* 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 *dfs(vector<int> A,int l,int r)
{
if(l>r)
return NULL;
int mid=(r+l)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=dfs(A,l,mid-1);
root->right=dfs(A,mid+1,r);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
if(A.size()==0)
return NULL;
int r,l,mid;
l=0,r=A.size()-1;
mid=(r+l)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=dfs(A,l,mid-1);
root->right=dfs(A,mid+1,r);
return root;
}
};