问题描述:
给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
注意事项
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 *sortedArrayToBST(vector<int> &A) {
// write your code here
if(A.size()==0) return NULL;
else return func(A,0,A.size()-1);
}
TreeNode* func(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=func(A,start,mid-1);
root->right=func(A,mid+1,end);
return root;
}
};
解题感悟:
一开始不知道二叉搜索树是怎么产生的,知道原理后就好做了。