给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
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: an integer array
* @return: A tree node
*/
TreeNode * sortedArrayToBST(vector<int> &A) {
// write your code here
if(!A.size())
return NULL;
int r=A.size()-1;
int l=0;
int m=(l+r)>>1;
TreeNode *root=subNode(A,l,r);
return root;
}
TreeNode *subNode(vector<int> A,int l,int r)
{
if(l>r)
return NULL;
int m=(l+r)>>1;
TreeNode *root=new TreeNode(A[m]);
root->left=subNode(A,l,m-1);
root->right=subNode(A,m+1,r);
return root;
}
};
lintcode_177_把排序数组转换为高度最小的二叉搜索树
原文:http://www.cnblogs.com/ygtzds/p/7751448.html