题目描述:
给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
注意事项
There may exist multiple valid solutions, return any of them.
样例:
给出数组 [1,2,3,4,5,6,7]
, 返回
4
/ \
2 6
/ \ / \
1 3 5 7
做题思路:类内调用递归函数。如果题目已给数组为空,则返回空,若不为空,则新建一个根结点,取数组中的中间数赋值给该根结点,并把数组中中间数左右的数值,赋给该根结点的左子树和右子树,递归完成后返回根结点。
关键代码:
class Solution {
public:
/**
* @param A: A sorted (increasing order) array
* @return: A tree node
*/
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
if(A.empty())
return NULL;
int s=0;int e=A.size()-1;
int m=(s+e)/2;
TreeNode *newroot=new TreeNode(A[m]);
newroot->left=sorted(A,s,m-1);
newroot->right=sorted(A,m+1,e);
return newroot;
}
TreeNode *sorted(vector<int> &A, int s, int e)
{ if(s>e)
return NULL;
int m=(s+e)/2;
TreeNode *newroot=new TreeNode(A[m]);
newroot->left=sorted(A,s,m-1);
newroot->right=sorted(A,m+1,e);
return newroot;
}
};
做题感想:这种类内编写递归函数的方式,是从我提交的的上一题那里了解的,这一题的刚开始编写的时候总是越界,就是在编写递归函数时,函数中的参数使用的范围不对,后来改了改,调了调就对了。这道题想法很容易想,但编写中容易出现超范围的问题。